Laravel CRUD - Part 2


Hi guys! This is the second part of my tutorial based on creating a CRUD apllication using Laravel. I think now, you have already followed me with the part of this tutorial. So, get ready to start the part 2! Before starting it, I will recap what we did in the previous article.
  1. Create view to input data with validations
  2. Create the view to display data from database
  3. Complete the index, create and store functions in resource controller
  4. Insert data to the database
What will we do today?

Edit, Update and Delete data connected to the database.

Let's go guys!


Step 1 - Create single view function in Controller

We have to implement the function to retrieve data of a particular user from database. For this, we need a controller function. So, place this code and update your CrudController.

public function show($id)
{
$user = User::find($id);
return view('show')->with('user',$user)->withTitle('User Details');
}


Step 2 - Create the single user view

resources/views/show.blade.php

@extends('master')
@section('content')
<div class="col-lg-12">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-8">
@include('messages')
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-lg-6" style="float: left;">
<img class="img-thumbnail" src="/storage/user_images/{{ $user->user_image}}">
</div>
<div class="col-lg-6" style="float: right;">
<ul class="list-group">
<li class="list-group-item"><b>User ID :</b> {{ $user->id }}</li>
<li class="list-group-item"><b>Name :</b> {{ $user->name }}</li>
<li class="list-group-item"><b>Email:</b> {{ $user->email }}</li>
<li class="list-group-item"><b>Created at :</b><br> {{ date('h: i a', strtotime($user->created_at) )}} on {{ date('F j, Y', strtotime($user->created_at) )}}</li>
<li class="list-group-item"><b>Updated at :</b><br> {{ date('h: i a', strtotime($user->created_at) )}} on {{ date('F j, Y', strtotime($user->updated_at) )}}</li><br>
<a href="/crud" style="float: right;" class="btn btn-dark btn-md">Back to users</a>
</ul>
</div>
</div>
<br>
</div>
</div>
</div>
<div class="col-lg-2"></div>
</div>
</div>
@endsection

When you click on view button in index.blade.php file, you will be directed to this output page.

Step 3 - Create edit function in controller

We have to fetch the data of each user into the edit view. Then the details of each and everyone will be displayed in a single view. so, the controller function is mentioned below. Add this code and update your CrudController.

public function edit($id)
{
$user = User::find($id);
return view('edit')->with('user',$user)->withTitle('Edit User');
}

Step 4  -  Create edit view

resources/views/edit.blade.php

@extends('master')
@section('content')
<div class="col-lg-12">
<div class="row">
<div class="col-lg-3"></div>
<div class="col-lg-6">
<h1 class="text-center">Edit a User</h1><br>
@include('messages')
<div class="card">
<div class="card-body">
{!! Form::open(['action' => ['CrudController@update', $user->id], 'method' => 'POST', 'enctype' => 'multipart/form-data']) !!}
<div class="form-group">
{{ Form::label('name', 'Your Name ', ['class' => 'form-label'] )}}
{{ Form::text('name', $user->name, ['class' => 'form-control', 'placeholder' => 'Give a Name', 'id' => 'name']) }}
</div>
<div class="form-group">
{{ Form::label('email', 'Your Email ', ['class' => 'form-label'] )}}
{{ Form::text('email', $user->email, ['class' => 'form-control', 'placeholder' => 'Give an email', 'id' => 'email']) }}
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-6">
<p>New Image</p><br>
{{ Form::file('user_image',['class' => 'dropify'])}}
</div>
<div class="col-lg-6">
<p>Existing Image</p><br>
<img src="/storage/user_images/{{$user->user_image}}" style="width: 200px; height: 200px;" id="post-img-edit">
</div>
</div>
<br><br>
</div>
<div class="row" style="margin-left: -5px;">
<div style="float: left;">
{{ Form::hidden('_method', 'PUT')}}
{{ Form::submit('Save changes', ['class' => 'btn btn-success btn-md']) }}
{!! Form::close() !!}
</div>
<div style="float: right;">
<a href="/crud/{{ $user->id }}" class="btn btn-dark btn-md">Cancel</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-3"></div>
</div>
</div>
@endsection

This is the output you should get after this step...
Still you will get errors when you try to load pages. Now we have to complete update function.

Step 5 -  Create update function

When user data is loaded in edit view, there should be a way to update and save the new data. Since we are storing images, we have to allocate a space to upload the new image also. Add this code to the controller - CrudController.

public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'user_image' => 'image|nullable|max:1999'
]);
// file upload
if($request->hasFile('user_image')){
$fileNameWithExt = $request->file('user_image')->getClientOriginalName();
// get file name
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
// get extension
$extension = $request->file('user_image')->getClientOriginalExtension();
// new name
$fileNameToStore = $filename.'_'.time().'.'.$extension;
// upload
$path = $request->file('user_image')->storeAs('public/user_images', $fileNameToStore);
}
$user = User::find($id);
$user->name = $request->input('name');
$user->email = $request->input('email');

if($request->hasFile('user_image')){
$user->user_image = $fileNameToStore;
}

$user->save();
// redirect to the create page with success message
return redirect('/crud')->with('success', 'User updated');
}

After this step, you can update the data when you click on save changes button. All the updated data will be saved to the database.

Step 6  -  Create Delete function in controller

This is the last step. After we create a user, there should be a way remove a user from database. For this, we don't need a view. Implementing the function is enough! Place this code in CrudController and update it.

public function destroy($id)
{
$user = User::find($id);
if($user->user_image != 'noimage.jpg'){
Storage::delete('public/user_images/'.$user->user_image);
}
$user->delete();

return redirect('/crud')->with('success', 'User Deleted');
}

That's all!!!! Now you can test delete function from the index view. Click on delete button and check whether the user is removed or not from database.

Final version - CrudController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Storage;

class CrudController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::orderBy('id','desc')->paginate(5);
return view('index',['users' => $users])->withTitle('Users in Database');
}

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

/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// validate inputs
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'user_image' => 'image|nullable|max:1999'
]);
// file upload
if($request->hasFile('user_image')){
$fileNameWithExt = $request->file('user_image')->getClientOriginalName();
// get file name
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
// get extension
$extension = $request->file('user_image')->getClientOriginalExtension();

$fileNameToStore = $filename.'_'.time().'.'.$extension;
// upload
$path = $request->file('user_image')->storeAs('public/user_images', $fileNameToStore);
}
else{
$fileNameToStore = 'noimage.jpg';
}
// create user
$user = new User;
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->user_image = $fileNameToStore;
$user->save();
// redirect to the create page with success message
return redirect('/crud/create')->with('success', 'User created');
}

/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::find($id);
return view('show')->with('user',$user)->withTitle('User Details');
}

/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::find($id);
return view('edit')->with('user',$user)->withTitle('Edit User');
}

/**
* 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, [
'name' => 'required',
'email' => 'required',
'user_image' => 'image|nullable|max:1999'
]);
// file upload
if($request->hasFile('user_image')){
$fileNameWithExt = $request->file('user_image')->getClientOriginalName();
// get file name
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
// get extension
$extension = $request->file('user_image')->getClientOriginalExtension();

$fileNameToStore = $filename.'_'.time().'.'.$extension;
// upload
$path = $request->file('user_image')->storeAs('public/user_images', $fileNameToStore);
}
$user = User::find($id);
$user->name = $request->input('name');
$user->email = $request->input('email');

if($request->hasFile('user_image')){
$user->user_image = $fileNameToStore;
}

$user->save();
// redirect to the create page with success message
return redirect('/crud')->with('success', 'User updated');
}

/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$user = User::find($id);
if($user->user_image != 'noimage.jpg'){
Storage::delete('public/user_images/'.$user->user_image);
}
$user->delete();

return redirect('/crud')->with('success', 'User Deleted');
}
}

You have completed the CRUD application now!

I think I have told and explained everything you need to create these four main functionalities. This is the end of the tutorial. Try this put and ask anything that you want to get to know about Laravel CRUD functions.

Good Luck!





Admin Semoga Informasi Yang Diberikan Melalui Web Ini Dapat Bermanfaat Bagi Saudara/i

No comments for "Laravel CRUD - Part 2"