Mohamed Benhida

admin@devma.net

December 8, 2017

CRUD(Create,Read,Update,Delete) in Laravel

We use CRUD (Create,Read,Update,Delete) in every project we build. 

After We begin each project in laravel we need to add database credentials in .env 

cp .env.example .env 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=

Now we create Post model using this command tag -m is for creating a migration related to this model

php artisan make:model Post -m

Each time we create a migration with model the table name will be model name in plural like in our example we will have table named posts

  public function up()
    {
        // Create table for storing roles
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('category');
            $table->string('content');
            $table->timestamps(); //created_at & updated_at columns
        });
    }

Now we create PostController using this commande with -r tag that will have all the necessary methods that we will need.

php artisan make:controller PostController -r

Create : 

PostController -

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $post = Post::get();
        return view('index')->with('posts',$post);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('create');
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
          'title' => 'required|max:20',
          'category' => 'required|min:5|max:20',
          'content' => 'required|min:10'
        ]);
        $post = new Post();
        $post->title = $request->title;
        $post->category = $request->category;
        $post->content = $request->content;
        $post->save();

        return redirect()->route('index');
    }

routes/web.php

  Route::get('/add',[
    'uses' => 'PostController@create',
    'as' => 'create'
  ]);
  Route::post('/add',[
    'uses' => 'PostController@store',
    'as' => 'store'
  ]);

create.blade.php


  <div class="col-md-4 col-md-offset-4">
      <form class="" action="{{ route('store')}}" method="post">
        {{ csrf_field() }}

        @if(count($errors) > 0)
          <div class="alert alert-danger">
              @foreach($errors->all() as $errors)
                <p>{{ $errors }}</p>
              @endforeach
          </div>
        @endif

        <div class="form-group">
          <label for="title">Title : </label>
          <input type="text" name="title" class="form-control" value="{{ old('title') }}">
        </div>
        <div class="form-group">
          <label for="category">Category : </label>
          <input type="text" name="category" class="form-control" value="{{ old('category') }}">
        </div>
        <div class="form-group">
          <label for="content">Content : </label>
          <textarea name="content" rows="8" cols="80">{{ old('content') }}</textarea>
        </div>
        <button type="submit" class="btn btn-success" name="button">Save</button>
      </form>
  </div>

Read :

PostController

public function show($id)
    {
        $post = Post::find($id);
        return view('single')->with('post',$post);
    }

single.blade.php

{{ $post }}

routes/web.php

Route::get('post/{id}',[
  'uses' => 'PostController@show',
  'as' => 'single'
]);

Update :

PostController

 public function edit($id)
    {
        $post = Post::find($id);
        return view('post_edit')->with('post',$post);
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
      $this->validate($request,[
        'title' => 'required|max:20',
        'category' => 'required|min:5|max:20',
        'content' => 'required|min:10'
      ]);
      $post = Post::find($id);
      $post->title = $request->title;
      $post->category = $request->category;
      $post->content = $request->content;
      $post->update();

      return redirect()->route('single_post',$post->id);
    }

routes/web.php

Route::get('/modifier',[
  'uses' => 'PostController@edit',
  'as' => 'edit'
]);
Route::post('/call_modifier',[
  'uses' => 'PostController@update',
  'as' => 'update'
]);
    

edit.blade.php

  <div class="col-md-4 col-md-offset-4">
       <form class="" action="{{ route('update',$post->id)}}" method="post">
         {{ csrf_field() }}
         @if(count($errors) > 0)
           <div class="alert alert-danger">
               @foreach($errors->all() as $errors)
                 <p>{{ $errors }}</p>
               @endforeach
           </div>
         @endif
         <div class="form-group">
           <label for="title">Title : </label>
           <input type="text" name="title" class="form-control" value="{{ $post->title }}">
         </div>
         <div class="form-group">
           <label for="category">Category : </label>
           <input type="text" name="category" class="form-control" value="{{ $post->category }}">
         </div>
         <div class="form-group">
           <label for="content">Content : </label>
           <textarea name="content" rows="8" cols="80">{{ $post->content }}</textarea>
         </div>
         <button type="submit" class="btn btn-success" name="button">Save</button>
       </form>
   </div>

Delete :

Postcontroller

public function destroy($id)
    {
        $post = Post::find($id);
        $post->delete();
        return redirect()->route('index');
    }

routes/web.php

Route::get('delete/{id}',[
  'uses' => 'PostController@destroy',
  'as' => 'destroy'
]);

 I Hope your Enjoyed Reading this Post.

© Mohamed Benhida.

Blog | Packages | About