Laravel CRUD with blade and authentification and seeder
Tags: webdev, laravel, bootstrap
Published: 2023-05-09 15:46:47

Lets start with installing fresh laravel using below command:

```php
composer create-project  laravel/laravel laravel-crud
```

Now lets create a new lara-crud database and configure database credentials in .env file


```javascript
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tplaravel2
DB_USERNAME=root
DB_PASSWORD=
```
**
Implement Authentication**
 

**we need to install laravel-ui package in development mode. **

cd laravel-crud

```javascript
composer require laravel/ui --dev
```

![install laravel-ui](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/av8cj4ftksxwbze74ugp.png)

```javascript
php artisan ui bootstrap --auth
```

```javascript
npm install 
```
then let run 
```javascript
npm run dev
```

![npm run dev](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t9g7r02wild88w9axlkt.png)

Remember to keep the console running with the npm run dev command while you are working on your application's frontend, as it ensures that any changes you make to the assets are automatically compiled and reflected in your application.


This will install a layout registration and login views, as well as routes for all authentication end-points. It will also use HomeController to handle post-login requests to your application’s dashboard.

```javascript
php artisan migrate
```

now you can run your project to check your login page and register ready to go !

login

![login](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x73gd5jq75d7acsfugp2.png)

register 

![register ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/82j2y3jlz7eyoe0ll2ky.png)

let update our welcome.blade.php with this code below :

```javascript
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>My App</title>

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

    <!-- Styles -->
    <style>
        html,
        body {
            background-color: #fff;
            color: #636b6f;
            font-family: 'Nunito', sans-serif;
            font-weight: 200;
            height: 100vh;
            margin: 0;
        }

        .full-height {
            height: 100vh;
        }

        .flex-center {
            align-items: center;
            display: flex;
            justify-content: center;
        }

        .position-ref {
            position: relative;
        }

        .top-right {
            position: absolute;
            right: 10px;
            top: 18px;
        }

        .content {
            text-align: center;
        }

        .title {
            font-size: 84px;
        }

        .links>a {
            color: #636b6f;
            padding: 0 25px;
            font-size: 13px;
            font-weight: 600;
            letter-spacing: .1rem;
            text-decoration: none;
            text-transform: uppercase;
        }

        .m-b-md {
            margin-bottom: 30px;
        }
    </style>
</head>

<body>
    <div class="flex-center position-ref full-height">
        <div class="content">
            <div class="title m-b-md">
                My tutorial App
            </div>

            <div class="links">
                @if (Route::has('login'))
                @auth
                <a href="{{ url('/todo') }}">Home</a>
                @else
                <a href="{{ route('login') }}">Login</a>

                @if (Route::has('register'))
                <a href="{{ route('register') }}">Register</a>
                @endif
                @endauth
                @endif
            </div>
        </div>
    </div>
</body>

</html>
```

after runing your project :

```javascript
php artisan serve
```

http://127.0.0.1:8000/login

![login page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xw2o22yl8ej91uutflzl.png)

Create Todo Model, Migration & Controller in one cmd line : 

```
php artisan make:model Todo -mcr
```

this cmd will create model Todo and table todos and TodoController

```javascript
  public function up()
    {
        Schema::create('todos', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('description');
            $table->integer('user_id');
            $table->enum('status', ['pending','completed']);
            $table->timestamps();
        });
    }
```

php artisan migrate


**Here we have used $fillable property for mass assignable fields.**

```
class Todo extends Model
{
    protected $fillable = ['title', 'description', 'user_id', 'status'];
}
```

Next we need to register resourceful route to access all resource methods from TodoController. Open  routes/web.php file and add route code.


go to routes/web.php

```javascript
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\TodoController;
Auth::routes();
Route::resource('/todo', TodoController::class);
```
or 

```javascript
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\TodoController;
Auth::routes();



Route::get('/todo', [TodoController::class, 'index'])->name('todo.index');
Route::post('/todo', [TodoController::class, 'store'])->name('todo.store');
Route::get('/todo/{todo}/edit', [TodoController::class, 'edit'])->name('todo.edit');
Route::delete('/todo/{todo}', [TodoController::class, 'destroy'])->name('todo.destroy');
Route::put('/todo/{todo}', [TodoController::class, 'update'])->name('todo.update');
Route::get('/todo/create', [TodoController::class, 'create'])->name('todo.create');
```


**Update Auth Redirect Routes**

after creating our TodoController let make some changes in login and register Controller

```

 // protected $redirectTo = RouteServiceProvider::HOME;

  protected $redirectTo = '/todo';
   
```

The reason behind updating this route is that it will redirect to todo list page after successful registration and login of user. 

Normally it redirect to dashboard page of HomeController but we dont need it so we use different route for this reason.


now let create our first user with seeder 

```
php artisan make:seeder UsersTableSeeder
```

let update our Usertableseeder : 

```javascript
<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;
class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        //
        User::create(
            [
                "name" => "user",
                "email" => "user1@gmail.com",
                "password" => "12345678",
            ]
        );
    }
}

```

or store multiple user 

```javascript
 $users = [
        [
            "name" => "user1",
            "email" => "user1@gmail.com",
            "password" => "12345678",
        ],
        [
            "name" => "user2",
            "email" => "user2@gmail.com",
            "password" => "12345678",
        ],
        // Add more user arrays as needed
    ];

    foreach ($users as $userData) {
        User::create($userData);
    }
```




add this line to DatabaseSeeder : 

```javascript
     $this->call(UsersTableSeeder::class);
```
or we can generate randomly new fake users

```javascript
        $factory = new UserFactory();
        $factory->count(10)->create();
```
run the following command:

```javascript
php artisan db:seed --class=UsersTableSeeder
```


**Todo list blades : **

create a folder in view called todo and create those file : 

* list.blade.php

```javascript
@extends('layouts.app')
@section('content')
<div class="container">
  <br>
    <div class="row justify-content-center">
        <div class="col-md-6">
            <h2>Todos List</h2>
        </div>
        <div class="col-md-6">
            <div class="float-right">
                <a href="{{ route('todo.create') }}" class="btn btn-primary"><i class="fa fa-plus"></i> Add new todo</a>
            </div>
        </div>
        <br>
        <div class="col-md-12">
            @if (session('success'))
                <div class="alert alert-success" role="alert">
                    {{ session('success') }}
                </div>
            @endif
            @if (session('error'))
                <div class="alert alert-danger" role="alert">
                    {{ session('error') }}
                </div>
            @endif
            <table class="table table-bordered">
        <thead class="thead-light">
          <tr>
            <th width="5%">#</th>
            <th>Task Name</th>
            <th width="10%"><center>Task Status</center></th>
            <th width="14%"><center>Action</center></th>
          </tr>
        </thead>
        <tbody>
          @forelse ($todos as $todo)
              <tr>
              <th>{{ $todo->id }}</th>
              <td>{{ $todo->title }}</td>
              <td><center>{{ $todo->status }}</center></td>
              <td>
                <div class="action_btn">
                  <div class="action_btn">
                    <a href="{{ route('todo.edit', $todo->id)}}" class="btn btn-warning">Edit</a>
                  </div>
                  <div class="action_btn margin-left-10">
                    <form action="{{ route('todo.destroy', $todo->id)}}" method="post">
                      @csrf
                      @method('DELETE')
                      <button class="btn btn-danger" type="submit">Delete</button>
                    </form>
                  </div>
                </div>
              </td>
            </tr>
          @empty
              <tr>
              <td colspan="4"><center>No data found</center></td>
            </tr>
          @endforelse
        </tbody>
      </table>
        </div>
    </div>
</div>
@endsection
```



![todo list view](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rq2o2cvmzgx6khtlonf0.png)




* add.blade.php

```javascript
@extends('layouts.app')
@section('content')
<div class="container">
  <br>
    <div class="row justify-content-center">
        <div class="col-md-6">
            <h2>Add Todo</h2>
        </div>
        <div class="col-md-6">
            <div class="float-right">
                <a href="{{ route('todo.index') }}" class="btn btn-primary">Back</a>
            </div>
        </div>
        <br>
        <div class="col-md-12">
            @if (session('success'))
                <div class="alert alert-success" role="alert">
                    {{ session('success') }}
                </div>
            @endif
            @if (session('error'))
                <div class="alert alert-error" role="alert">
                    {{ session('error') }}
                </div>
            @endif
      <form action="{{ route('todo.store') }}" method="POST">
        @csrf
        <div class="form-group">
          <label for="title">Title:</label>
          <input type="text" class="form-control" id="title" name="title">
        </div>
        <div class="form-group">
          <label for="description">Description:</label>
          <textarea name="description" class="form-control" id="description" rows="5"></textarea>
        </div>
        <div class="form-group">
        <label for="status">Select todo status</label>
        <select class="form-control" id="status" name="status">
          <option value="pending">Pending</option>
          <option value="completed">Completed</option>
        </select>
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
        </div>
    </div>
</div>
@endsection
```


![add page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wo9sahsqr7lwhawrl7e3.png)




* edit.blade.php

```javascript
@extends('layouts.app')
@section('content')
<div class="container">
    <br>
    <div class="row justify-content-center">
        <div class="col-md-6">
            <h2>Edit Todo</h2>
        </div>
        <div class="col-md-6">
            <div class="float-right">
                <a href="{{ route('todo.index') }}" class="btn btn-primary">Back</a>
            </div>
        </div>
        <br>
        <div class="col-md-12">
            @if (session('success'))
            <div class="alert alert-success" role="alert">
                {{ session('success') }}
            </div>
            @endif
            @if (session('error'))
            <div class="alert alert-error" role="alert">
                {{ session('error') }}
            </div>
            @endif
            <form action="{{ route('todo.update', ['todo' => $todo->id]) }}" method="POST">
                @csrf
                @method('PUT')
                <div class="form-group">
                    <label for="title">Title:</label>
                    <input type="text" class="form-control" id="title" name="title" value="{{ $todo->title }}">
                </div>
                <div class="form-group">
                    <label for="description">Description:</label>
                    <textarea name="description" class="form-control" id="description" rows="5">{{ $todo->description }}</textarea>
                </div>
                <div class="form-group">
                    <label for="status">Select todo status</label>
                    <select class="form-control" id="status" name="status">
                        <option value="pending" @if ($todo->status == 'pending') selected @endif>Pending</option>
                        <option value="completed" @if ($todo->status == 'completed') selected @endif>Completed</option>
                    </select>
                </div>
                <button type="submit" class="btn btn-info">Submit</button>
            </form>
        </div>
    </div>
</div>
@endsection
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ecush8zx6vxv01g10dk.png)





* view.blade.php

```javascript
@extends('layouts.app')
@section('content')
<div class="container">
  <br>
    <div class="row justify-content-center">
        <div class="col-md-6">
            <h2>Todo Details</h2>
        </div>
        <div class="col-md-6">
            <div class="float-right">
                <a href="{{ route('todo.index') }}" class="btn btn-primary">Back</a>
            </div>
        </div>
        <br>
        <div class="col-md-12">
            <br><br>
            <div class="todo-title">
                <strong>Title: </strong> {{ $todo->title }}
            </div>
            <br>
            <div class="todo-description">
                <strong>Description: </strong> {{ $todo->description }}
            </div>
            <br>
            <div class="todo-description">
                <strong>Status: </strong> {{ $todo->status }}
            </div>
        </div>
    </div>
</div>
@endsection
```


**Todo list Controller with all Crud Methods : **

```javascript
<?php

namespace App\Http\Controllers;

use App\Models\Todo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class TodoController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $userId = Auth::user()->id;
        $todos = Todo::where(['user_id' => $userId])->get();
        return view('todo.list', ['todos' => $todos]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('todo.add');
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $userId = Auth::user()->id;
        $input = $request->input();
        $input['user_id'] = $userId;
        $todoStatus = Todo::create($input);

        if ($todoStatus) {
            $message = 'Todo successfully added';
            $type = 'success';
        } else {
            $message = 'Oops, something went wrong. Todo not saved';
            $type = 'error';
        }

        return redirect('todo')->with($type, $message);
    }
    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        $userId = Auth::user()->id;
        $todo = Todo::where(['user_id' => $userId, 'id' => $id])->first();
        if (!$todo) {
            return redirect('todo')->with('error', 'Todo not found');
        }
        return view('todo.view', ['todo' => $todo]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $userId = Auth::user()->id;
        $todo = Todo::where(['user_id' => $userId, 'id' => $id])->first();
        if ($todo) {
            return view('todo.edit', ['todo' => $todo]);
        } else {
            return redirect('todo')->with('error', 'Todo not found');
        }
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $userId = Auth::user()->id;
        $todo = Todo::find($id);
        if (!$todo) {
            return redirect('todo')->with('error', 'Todo not found.');
        }
        $input = $request->input();
        $input['user_id'] = $userId;
        $todoStatus = $todo->update($input);
        if ($todoStatus) {
            return redirect('todo')->with('success', 'Todo successfully updated.');
        } else {
            return redirect('todo')->with('error', 'Oops something went wrong. Todo not updated');
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $userId = Auth::user()->id;
        $todo = Todo::where(['user_id' => $userId, 'id' => $id])->first();
        $respStatus = $respMsg = '';
        if (!$todo) {
            $respStatus = 'error';
            $respMsg = 'Todo not found';
        }
        $todoDelStatus = $todo->delete();
        if ($todoDelStatus) {
            $respStatus = 'success';
            $respMsg = 'Todo deleted successfully';
        } else {
            $respStatus = 'error';
            $respMsg = 'Oops something went wrong. Todo not deleted successfully';
        }
        return redirect('todo')->with($respStatus, $respMsg);
    }
}

```



Link Github for this project :