.


Divya


Laravel CURD example


Step 1 : Install Laravel
Step 2: Update Database Configuration
Step 3: Create Table
Step 4: Create Resource Route
Step 5: Create Controller and Model
Step 6: Create Blade Files

step 1-

    composer create-project --prefer-dist laravel/laravel myFstLaravel

step 2-

    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=LaravelDemo
    DB_USERNAME=root
    DB_PASSWORD=
    
    set the above value in .env file.
    make sure you mysql is runnig and LaravelDemo db exists.

Step 3-

    for create table we use migration command
    help command
     php artisan make:migration --help --> it will show help related migration argument
    syntax
    php artisan make:migration <fileName> --create=<tableName>
    example
    
    php artisan make:migration user_data --create=user_data
    or
    php artisan make:migration --path=/database/migrations/user_data  user_data --create=user_data
    migration file created on user_data folder.
    
    put the table field in user_data migration file
    path = database/migration/ 
    
    $table->increments('id');
    $table->string('name');
    $table->string('email');
    $table->timestamps();
    
    save the file and execute one more command to migrate table to db
    php artisan migrate  
    or
    php artisan migrate --path=/database/migrations/user_data/
    

step 4-

    Create Resource Route or create Route
    Actually create Resource route give us shortcut to create route
    example
    Route::resource('/userData','UserDataController');
    
    The above single line is equivalent of these following routes
    // convention of laravel routes
    // Route::get('/userData','UserDataController@index');
    // Route::get('/userData/create','UserDataController@create');
    // Route::get('/userData/{userData}','UserDataController@show');
    // Route::post('/userData','UserDataController@store');
    // Route::get('/userData/{userData}/edit','UserDataController@edit');
    // Route::patch('/userData/{userData}','UserDataController@update');
    // Route::delete('/userData/{userData}','UserDataController@destroy');
    
    we can see routes in terminal 
    php artisan route : list
    

step 5-

    php artisan help make:controller -> It'll show the list of argument

    To create controller and model just execute the following command
    
    php artisan  make:controller UserDataController -r -m UserData
    
    terminal will ask :  A App\UserData model does not exist. Do you want to generate it? 
    (yes/no) [yes]: type yes and press enter.

    

UserDataController.php

<?php

namespace App\Http\Controllers;

use App\UserData;
use Illuminate\Http\Request;

class UserDataController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $userData = UserData::latest()->paginate(5);
  
        return view('userData.index',compact('userData'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('userData.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required',
        ]);
  
        UserData::create($request->all());
   
        return redirect()->route('userData.index')
                        ->with('success','User created successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\UserData  $userData
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $userData = UserData::find($id);
        return view('userData.show',compact('userData'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\UserData  $userData
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $userData = UserData::find($id);
        return view('userData.edit',compact('userData','id'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\UserData  $userData
     * @return \Illuminate\Http\Response
     */
    public function update($id)
    {
        $userData = UserData::find($id);
        $userData->name = request('name');
        $userData->email = request('email');
        $userData->save();
        // $request->validate([
        //     'name' => 'required',
        //     'email' => 'required',
        // ]);
        // $userData->update($request->all());
  
        return redirect()->route('userData.index')
                        ->with('success','User updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\UserData  $userData
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        UserData::find($id)->delete();
  
        return redirect()->route('userData.index')
                        ->with('success','User deleted successfully');
    }
}

UserData.php (modal)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserData extends Model
{
    protected $table = 'user_data';
    protected $fillable = [
        'name', 'email'
    ];
}

layout.blade.php

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <title>LaravelDemo</title>
    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!-- Style --> 

</head>
<body>
  
<div class="container">
    @yield('content')
</div>
   
</body>
</html>

index.blade.php

       @extends('userData.layout')
 
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel Demo</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('userData.create') }}"> Create New User</a>
            </div>
        </div>
    </div>
   
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif
   
    <table class="table table-bordered">
        <tr>
            <th>No</th>
            <th>Name</th>
            <th>email</th>
            <th width="280px">Action</th>
        </tr>
        @foreach ($userData as $uData)
        <tr>
            <td>{{ ++$i }}</td>
            <td>{{ $uData->name }}</td>
            <td>{{ $uData->email }}</td>
            <td>
                <form action="{{ route('userData.destroy',$uData->id) }}" method="POST">
                   
                    <a class="btn btn-info" href="{{ route('userData.show',$uData->id) }}">Show</a>

 
    
                    <a class="btn btn-primary" href="{{ route('userData.edit',$uData->id) }}">Edit</a>
                    <!-- SUPPORT ABOVE VERSION 5.5 -->
                    {{-- @csrf
                    @method('DELETE') --}} 
                    
                    {{ csrf_field() }}
                    {{ method_field('DELETE') }}
                  
      
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </table>
  
    {!! $userData->links() !!}
      
@endsection 

create.blade.php

      @extends('userData.layout')
  
@section('content')
<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>Add New User</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-primary" href="{{ route('userData.index') }}"> Back</a>
        </div>
    </div>
</div>
   
@if ($errors->any())
    <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
   
<form action="{{ route('userData.store') }}" method="POST">
    {{ csrf_field() }}
  
     <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                <input type="text" name="name" class="form-control" placeholder="Name">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Email Id:</strong>
                <input type="text" class="form-control" name="email" placeholder="Email Id">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>
   
</form>
@endsection  

edit.blade.php

       @extends('userData.layout')
   
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Edit User</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('userData.index') }}"> Back</a>
            </div>
        </div>
    </div>
   
    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
  
    <form action="{{ route('userData.update',$userData->id) }}" method="POST">
        {{ csrf_field() }}
        {{ method_field('PATCH') }}
   
         <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Name:</strong>
                    <input type="text" name="name" value="{{ $userData->name }}" class="form-control" placeholder="Name">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Email ID:</strong>
                    <input type="text" class="form-control" name="email" value ="{{ $userData->email }}" placeholder="Email ID">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 text-center">
              <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>
   
    </form>
@endsection 

show.blade.php

     @extends('userData.layout')

@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2> Show User</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('userData.index') }}"> Back</a>
            </div>
        </div>
    </div>
   
    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                {{ $userData->name }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Details:</strong>
                {{ $userData->email }}
            </div>
        </div>
    </div>
@endsection
   


.