Laravel Project - Users table view, Insert, Update, Delete, Collective Form

Laravel Project - Users table view, Insert, Update, Delete, Collective Form

Instructor-svgAl-Mamun Sarkar
Aug 24 , 2020
  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram

এই লেসনে User এর লিস্ট দেখানো User Insert, Update, Delete করা দেখানো হয়েছে। Resource Route ও Collective Form নিয়ে আলোচনা করা হয়েছে। 

 

Source code:

 

Github Project:

https://github.com/almamuncsit/mini_pos

 

Artisan Command:

php artisan make:controller UsersController --resource
php artisan make:request CreateUserRequest
php artisan make:request UpdateUserRequest

 

Routes:

Route::resource('users', 'UsersController', ['except' => ['show'] ]);

// Route::resource('users', 'UsersController', ['only' => ['show', 'destroy'] ]);
// Route::get('users', 'UsersController@index');
// Route::get('users/{id}', 'UsersController@show');
// Route::get('users/create', 'UsersController@create');
// Route::post('users', 'UsersController@store');
// Route::get('users/{id}/edit', 'UsersController@edit');
// Route::put('users/{id}', 'UsersController@update');
// Route::delete('users/{id}', 'UsersController@destroy');

 

UsersController:

namespace App\Http\Controllers;

use App\Group;
use App\Http\Requests\CreateUserRequest;
use App\Http\Requests\UpdateUserRequest;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class UsersController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->data['users'] = User::all();

        return view('users.users', $this->data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $this->data['groups']       = Group::arrayForSelect();
        $this->data['mode']         = 'create';
        $this->data['headline']     = 'Add New User';

        return view('users.form', $this->data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CreateUserRequest $request)
    {
        $formData = $request->all();
        if( User::create($formData) ) {
            Session::flash('message', 'User Created Successfully');
        }
        
        return redirect()->to('users');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $this->data['user']         = User::findOrFail($id);
        $this->data['groups']       = Group::arrayForSelect();
        $this->data['mode']         = 'edit';
        $this->data['headline']     = 'Update Information';

        return view('users.form', $this->data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateUserRequest $request, $id)
    {
        $data               = $request->all();

        $user               = User::find($id);
        $user->group_id     = $data['group_id'];
        $user->name         = $data['name'];
        $user->email        = $data['email'];
        $user->phone        = $data['phone'];
        $user->address      = $data['address'];

        if( $user->save() ) {
            Session::flash('message', 'User Updated Successfully');
        }
        
        return redirect()->to('users');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if( User::find($id)->delete() ) {
            Session::flash('message', 'User Deleted Successfully');
        }
        
        return redirect()->to('users');
    }
}

 

User Mode (User.php):

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $fillable = ['group_id', 'name', 'phone', 'email', 'address'];

    public function group()
    {
    	return $this->belongsTo(Group::class);
    }

}

 

User Group Mode (Group.php):

namespace App;

use Illuminate\Database\Eloquent\Model;

class Group extends Model
{
    protected $fillable = ['title'];


    public function users()
    {
        return $this->hasMany(User::class);
    }

    /**
    * Getting array for select option
    **/
    public static function arrayForSelect() {
    	$arr = [];
    	$groups = Group::all();
        foreach ($groups as $group) {
            $arr[$group->id] = $group->title;
        } 

        return $arr;
    }
    
}

 

CreateUserRequest:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CreateUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'group_id' => 'required',
            'name' => 'required|string',
            'phone' => 'required|numeric|unique:users',
            'email' => 'nullable|email|unique:users',
        ];
    }
}

 

UpdateUserRequest:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UpdateUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'group_id' => 'required',
            'name' => 'required|string',
            'phone' => 'required|numeric',
            'email' => 'nullable|email',
        ];
    }
}

 

users/users.blade.php

@extends('layout.main')

@section('main_content')

	<div class="row clearfix page_header">
		<div class="col-md-6">
			<h2> Users </h2>		
		</div>
		<div class="col-md-6 text-right">
			<a class="btn btn-info" href="{{ url('users/create') }}"> <i class="fa fa-plus"></i> New user </a>
		</div>
	</div>

	<!-- DataTales Example -->
	  <div class="card shadow mb-4">
	    <div class="card-header py-3">
	      <h6 class="m-0 font-weight-bold text-primary">Users</h6>
	    </div>
	    <div class="card-body">
	      <div class="table-responsive">
	        <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
	          <thead>
	            <tr>
	              <th>ID</th>
	              <th>Group</th>
	              <th>Name</th>
	              <th>Email</th>
	              <th>Phone</th>
	              <th>Address</th>
	              <th class="text-right">Actions</th>
	            </tr>
	          </thead>
	          <tfoot>
	            <tr>
	              <th>ID</th>
	              <th>Group</th>
	              <th>Name</th>
	              <th>Email</th>
	              <th>Phone</th>
	              <th>Address</th>
	              <th class="text-right">Actions</th>
	            </tr>
	          </tfoot>
	          <tbody>
	          	@foreach ($users as $user)
		            <tr>
		              <td> {{ $user->id }} </td>
		              <td> {{ $user->group->title }} </td>
		              <td> {{ $user->name }} </td>
		              <td> {{ $user->email }} </td>
		              <td> {{ $user->phone }} </td>
		              <td> {{ $user->address }} </td>
		              <td class="text-right">
		              	
		              	<form method="POST" action=" {{ route('users.destroy', ['user' => $user->id]) }} ">
		              		<a class="btn btn-primary btn-sm" href="{{ route('users.edit', ['user' => $user->id]) }}"> 
			              	 	<i class="fa fa-edit"></i> 
			              	</a>
		              		@csrf
		              		@method('DELETE')
		              		<button onclick="return confirm('Are you sure?')" type="submit" class="btn btn-danger btn-sm"> 
		              			<i class="fa fa-trash"></i>  
		              		</button>	
		              	</form>
		              </td>
		            </tr>
	            @endforeach
	          </tbody>
	        </table>
	      </div>
	    </div>
	  </div>


@stop

 

users/form.blade.php

@extends('layout.main')

@section('main_content')

	@if ($errors->any())
	    <div class="alert alert-danger">
	        <ul>
	            @foreach ($errors->all() as $error)
	                <li>{{ $error }}</li>
	            @endforeach
	        </ul>
	    </div>
	@endif

	
	<h2> {{ $headline }} </h2>
	
	<div class="card shadow mb-4">
	    <div class="card-header py-3">
	      <h6 class="m-0 font-weight-bold text-primary">{{ $headline }}</h6>
	    </div>
	    <div class="card-body">
	    	<div class="row justify-content-md-center">
	    		<div class="col-md-8">
	    			@if($mode == 'edit')
	    				{!! Form::model($user, [ 'route' => ['users.update', $user->id], 'method' => 'put' ]) !!}
	    			@else
	    				{!! Form::open([ 'route' => 'users.store', 'method' => 'post' ]) !!}	
	    			@endif
	    			

					  <div class="form-group row">
					    <label for="name" class="col-sm-3 col-form-label">User Group <span class="text-danger">*</span> </label>
					    <div class="col-sm-9">
					      {{ Form::select('group_id', $groups, NULL, [ 'class'=>'form-control', 'id' => 'group', 'placeholder' => 'Select Group' ]) }}
					    </div>
					  </div>

					  <div class="form-group row">
					    <label for="name" class="col-sm-3 col-form-label">Name <span class="text-danger">*</span> </label>
					    <div class="col-sm-9">
					      {{ Form::text('name', NULL, [ 'class'=>'form-control', 'id' => 'name', 'placeholder' => 'Name' ]) }}
					    </div>
					  </div>

					  <div class="form-group row">
					    <label for="phone" class="col-sm-3 col-form-label">Phone <span class="text-danger">*</span>  </label>
					    <div class="col-sm-9">
					      {{ Form::text('phone', NULL, [ 'class'=>'form-control', 'id' => 'phone', 'placeholder' => 'Phone' ]) }}
					    </div>
					  </div>
					  
					  <div class="form-group row">
					    <label for="email" class="col-sm-3 col-form-label">Email</label>
					    <div class="col-sm-9">
					      {{ Form::text('email', NULL, [ 'class'=>'form-control', 'id' => 'email', 'placeholder' => 'Email' ]) }}
					    </div>
					  </div>
					  
					  <div class="form-group row">
					    <label for="address" class="col-sm-3 col-form-label">Address</label>
					    <div class="col-sm-9">
					      {{ Form::text('address', NULL, [ 'class'=>'form-control', 'id' => 'address', 'placeholder' => 'Address' ]) }}
					    </div>
					  </div>


					  <div class="mt-4 text-right">
					  	<button type="submit" class="btn btn-primary">Submit</button>	
					  </div>
					  
					{!! Form::close() !!}
	    		</div>
	    	</div>
	    </div>
	</div>
@stop