laravel 8 tutorial for beginners
Crud operation of laravel is the best way to learn which type methods into laravel and which type layouts and which type of coding style into laravel you know the basic every points if you follow the laravel crud operation tutorials
Steps:1
composer create-project --prefer-dist laravel/laravel blog
Steps:2
Setup your Database values into .env file of Root Folder
Create migration for table using below Command
php artisan make:migration create_portfolios_table --create=portfolios
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePortfoliosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('portfolios', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->longText('description');
$table->string('image');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('portfolios');
}
}
After this you have to run this command php artisan migrate
Step:4
We need resource routes defined into the routes/web.php file because we need crud operation
use App\Http\Controllers\PortfolioController;
Route::resource('portfolio', PortfolioController::class);
Now We need to create a controller as PortfolioController
apply below command for create new controller
php artisan make:controller PortfolioController --resource --model=Portfolio
after applying the above command it will create file into
app/Http/Controller/PortfolioController.php
above command we are using --resource - if you wanna learn more about this you can read this - laravel resource collection
Now copy below code and put all code into your app/Http/Controller/PortfolioController.php file
<?php
namespace App\Http\Controllers\Admin;
use App\Portfolio;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Datatables;
use Session;
use Mail;
use RealRashid\SweetAlert\Facades\Alert;
class PortfolioController extends Controller
{
private $data = array(
'route' => 'portfolio.',
'title' => 'Portfolio',
'menu' => 'Portfolio',
'breadcrumbs' => 'Home',
);
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('admin.portfolio.index',$this->data);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
return view('admin.portfolio.create',$this->data);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
try{
$post=$request->all();
$request->validate([
'name' => 'required',
'description' => 'required',
]);
if ($request->has('image')) {
$imageName = time()."_".$request->image->getClientOriginalName();
// dd($imageName);
$request->image->move(public_path('uploads/portfolio'), $imageName);
$post['image'] = $imageName;
}else{
Session::flash('error','Image field is required');
return redirect()->route('portfolio.index');
}
$CreateDetails = array(
'name' => $post['name'],
'description' => $post['description'],
'image' => $post['image'],
);
Portfolio::create($CreateDetails);
Alert::success('Portfolio Details', 'added successfully');
return redirect()->route('portfolio.index');
}
catch (\Exception $e ) {
Alert::error('Oops something went wrong', $e->getMessage());
return redirect()->route('portfolio.index');
}
}
/**
* Display the specified resource.
*
* @param \App\Portfolio $portfolio
* @return \Illuminate\Http\Response
*/
public function show(Portfolio $portfolio)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Portfolio $portfolio
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$data_edit = Portfolio::find($id);
return view('admin.portfolio.edit',$this->data,compact('data_edit'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Portfolio $portfolio
* @return \Illuminate\Http\Response
*/
public function update(Request $request,$id)
{
//
try{
$post=$request->all();
$request->validate([
'name' => 'required',
'description' => 'required',
]);
if ($request->has('image')) {
$imageName = time()."_".$request->image->getClientOriginalName();
$request->image->move(public_path('uploads/portfolio'), $imageName);
$post['image'] = $imageName;
}
if(!empty($post['image'])){
$UpdateDetails = array(
'name' => $post['name'],
'description' => $post['description'],
'image' => $post['image'],
);
}else{
$UpdateDetails = array(
'name' => $post['name'],
'description' => $post['description'],
);
}
Portfolio::where('id',$id)->update($UpdateDetails);
Alert::success('Portfolio Details', 'edited successfully');
return redirect()->route('portfolio.index');
}
catch (\Exception $e ) {
Alert::error('Oops something went wrong', $e->getMessage());
return redirect()->route('portfolio.index');
}
}
/**
* Remove the specified resource from storage.
*
* @param \App\Portfolio $portfolio
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
try{
$portfolio = Portfolio::find($id);
if(!empty($portfolio)){
Portfolio::where('id',$id)->delete();
Alert::success('Portfolio Details', 'Deleted successfully');
return redirect()->route('portfolio.index');
}else{
Alert::error('Oops something went wrong', 'please try again');
return redirect()->route('portfolio.index');
}
}catch (\Exception $e ) {
Alert::error('Oops something went wrong', $e->getMessage());
return redirect()->route('portfolio.index');
}
}
//ajax response
public function ajaxData(Request $request)
{
$query = Portfolio::select('*');
return Datatables::of($query)->addColumn('action', function ($page) {
return " <a href=".route($this->data['route'].'edit',$page->id)." class='btn btn-info' title='edit' data-original-title='View'><span style='color:#fff;font-size:15px;font-weight:800'>✎</span></a>
<a href='javascript:void(0);' onclick='deleteUser(\"".route('portfolio.delete',$page->id)."\")' class ='btn btn-danger' title='delete'><spna
i class='fa fa-trash'></span></a>";
})->make(true);
}
}
I used another method that is ajaxData methods which will help me to display ajax data list into the main list of admin page this function will help you defined list of ajax dynamic data
Step:6
After applying above command it will create model also in app/Portfolio.php file
Step:7
Create all below files in this folder resources/views/admin/portfolio
You need to create here admin/portfolio folder path because in the above controller we are giving this path into every method
Create Below files
1)index.blade.php -- for index method which is defined as the main list of portfolio with edit and delete and add button
2)create.blade.php -- for creating portfolio form display into this file
3)edit.blade.php -- for editing portfolio form
Step:8
Copy Below code to you resource/view/admin/portfolio/index.blade.php file
After applying above command it will create model also in app/Portfolio.php file
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Portfolio extends Model
{
//
protected $guarded = [];
}
Step:7
Create all below files in this folder resources/views/admin/portfolio
You need to create here admin/portfolio folder path because in the above controller we are giving this path into every method
Create Below files
1)index.blade.php -- for index method which is defined as the main list of portfolio with edit and delete and add button
2)create.blade.php -- for creating portfolio form display into this file
3)edit.blade.php -- for editing portfolio form
Step:8
Copy Below code to you resource/view/admin/portfolio/index.blade.php file
@extends('adminlte::page')
@section('title') {{ $title }} @endsection
@section('content_header')
<h1>{{ $title }}</h1>
<a href="{{ route($route."create") }}" type="submit" class="btn btn-success pull-right">Add {{$title}}</a>
<br/>
<br/>
@stop
@section('content')
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Image</th>
<th>Description</th>
<th width="280px">Action</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Id</th>
<th>Name</th>
<th>Image</th>
<th>Description
<th width="280px">Action</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.box-header -->
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
</div>
@endsection
@section('js')
<!-- DataTables -->
<script type='text/javascript'>
$(function() {
$('#example1').DataTable({
processing: true,
serverSide: true,
responsive: true,
ajax: "{!! route($route."ajaxData") !!}",
columns: [
{data: 'id', name: 'id' },
{data: 'name', name: 'name' },
{ data: 'image', name: 'image',
render: function( data, type, full, meta ) {
return "<img src=\"{{url(asset('public/uploads/portfolio'))}}/" + data + "\" height=\"50\"/>";
}
},
{data: 'description', name: 'description' },
{data: 'action', name: 'action', searchable: false, orderable : false,className : 'text-center'},
]
});
});
function deleteUser(url) {
if(confirm("Do you really want to delete this {{$title}} ?"))
window.location.href= url;
else
return false;
}
</script>
@endsection
Step:9
Copy Below code to you resource/view/admin/portfolio/create.blade.php file
@extends('adminlte::page')
@section('title') {{ $title }} @endsection
@section('content_header')
<h1>{{ $title }}</h1>
@stop
@section('content')
<form action="<?php print route($route . 'store'); ?>" method="POST" enctype="multipart/form-data" id="createForm">
<input type="hidden" name="_token" value="{{csrf_token()}}">
@if($errors->any())
<div class="alert alert-danger">
<p><strong>Error</strong></p>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="box box-default">
<div class="box-header with-border">
<h3 class="box-title">{{ $title }}</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="title">{{$title}} Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter {{$title}} Name">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="title">{{$title}} Description<span class="text-danger">*</span></label>
<textarea type="text" class="form-control" id="description" name="description" placeholder="Enter {{$title}} Description" rows="5"></textarea>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="title">{{$title}} Image<span class="text-danger">*</span></label>
<input type="file" name="image"/>
</div>
</div>
</div>
<!-- /.row -->
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="submit" value="submit" class="btn btn-primary"><i class="fa fa-save"></i> Submit</button>
<a href="{{ route($route.'index') }}"><button type="button" class="btn btn-default"><i class="fa fa-arrow-circle-left"></i> Cancel</button></a>
</div>
</div>
</form>
<script type="text/javascript">
$('#createForm').validate({ // initialize the plugin
rules: {
name: {
required: true,
maxlength: 255
},
description: {
required: true,
},
image: {
required: true,
},
},
errorPlacement: function(){
return false;
},
});
</script>
@endsection
Step:10
Copy Below code to you resource/view/admin/portfolio/edit.blade.php file
@extends('adminlte::page')
@section('title') {{ $title }} @endsection
@section('content_header')
<h1>{{ $title }}</h1>
@stop
@section('content')
<form action="<?php print route($route . 'update', $data_edit->id); ?>" method="POST" enctype="multipart/form-data" id="editForm">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<input type="hidden" name="_method" value="PATCH">
@if($errors->any())
<div class="alert alert-danger">
<p><strong>Opps Something went wrong</strong></p>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="box box-default">
<div class="box-header with-border">
<h3 class="box-title">{{ $title }}</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="title">{{$title}} Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="name" name="name" value="{{$data_edit->name }}" placeholder="Enter {{$title}} Name">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="title">{{$title}}<span class="text-danger">*</span></label>
<textarea type="text" class="form-control" id="description" name="description" placeholder="Enter {{$title}} Description"
rows="5">{{$data_edit->description }}</textarea>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="title">{{$title}}<span class="text-danger">*</span></label>
@if(!empty($data_edit->image))
<img src="{{asset('public/uploads/portfolio')}}/{{$data_edit->image}}" class="img-responsive" width="100"/>
<br/> <input type="file" name="image">
@else
<input type="file" name="image">
@endif
</div>
</div>
</div>
<!-- /.row -->
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="submit" value="submit" class="btn btn-sm btn-primary"><i class="fa fa-save"></i> Submit</button>
<a href="{{ route($route.'index') }}"><button type="button" class="btn btn-sm btn-default"><i class="fa fa-arrow-circle-left"></i>
Cancel</button></a>
</div>
</div>
</form>
<script type="text/javascript">
$('#editForm').validate({ // initialize the plugin
rules: {
name: {
required: true,
maxlength: 255
},
description: {
required: true,
},
},
errorPlacement: function(){
return false;
},
});
</script>
@endsection
Notice that I added one more thing into this forms that Validation Of Jquery, it will help you show one red border if any input box has wrong value or empty before submitting the form this jquery will fire on your forms like below screenshot
Output:
Now We are done with steps and Here is your Laravel 6 Crud Operation is Done now :)
Happy coding :)
If you need full code of Laravel 6 Crud Operation then click on this (Here Full Source Code available) -- CRUD Laravel 6
I hope this will work for you and easily understand for you.
Thank you.
Wow, amazing block structure! How long
ReplyDeleteHave you written a blog before? Working on a blog seems easy.
The overview of your website is pretty good, not to mention what it does.
In the content!
cracklie.net
Light Image Resizer Crack
Capture One 22 Pro Crack
YTD Video Downloader Pro Crack
iBackupBot Crack
WiFi Explorer Pro Crack
PhpStorm Crack
Thank you but i did not written blog before this is my first website to share my blogs
DeletePost a Comment