How to add "not found" result on search data on laravel 5.8 - laravel

Is there a way to add result "not found" if my data is not in the database ?
In my search button I want to add a result that: if the search doesn't conclude the data inside the defined form, the search must output data not found...
The search is working...
Here is my controller
pegawaicontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Pegawai;
class pegawaicontroller extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$pegawais = Pegawai::orderBy('id', 'ASC')->paginate(5);
return view('pegawai.index', compact('pegawais'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('pegawai.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, [
'kategori' => 'required',
'jabatan' => 'required',
'nama_pegawai' => 'required',
'alamat' => 'required',
'gambar_pegawai' => 'required'
]);
// upload file
$filename = time() . '.png';
$request->file('gambar_pegawai')->storeAs('public/images', $filename);
$pegawai = new Pegawai;
$pegawai->kategori = $request->input('kategori');
$pegawai->jabatan = $request->input('jabatan');
$pegawai->nama_pegawai = $request->input('nama_pegawai');
$pegawai->alamat = $request->input('alamat');
$pegawai->gambar_pegawai = $filename;
$pegawai->save();
// $pegawai = Pegawai::create($request->all());
return redirect()->route('pegawai.index')->with('message','Data berhasil dibuat!');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$pegawai = Pegawai::findOrFail($id);
return view('pegawai.show', compact('pegawai'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$pegawai = Pegawai::findOrFail($id);
return view('pegawai.edit', compact('pegawai'));
}
/**
* 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, [
'kategori' => 'required',
'jabatan' => 'required',
'nama_pegawai' => 'required',
'alamat' => 'required',
'gambar_pegawai' => 'required'
]);
// script delete tapii gagal
// if ($request->produk()->gambar_pegawai){
// Storage::delete('images/' . $request->produk()->gambar_pegawai);
// }
// update file
$filename = time() . '.png';
$request->file('gambar_pegawai')->storeAs('public/images', $filename);
$pegawai = Pegawai::find($id);
$pegawai->kategori = $request->input('kategori');
$pegawai->jabatan = $request->input('jabatan');
$pegawai->nama_pegawai = $request->input('nama_pegawai');
$pegawai->alamat = $request->input('alamat');
$pegawai->gambar_pegawai = $filename;
$pegawai->save();
// $pegawai = Pegawai::findOrFail($id)->update($request->all());
return redirect()->route('pegawai.index')->with('message', 'Data berhasil diubah!');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$pegawai = Pegawai::findOrFail($id)->delete();
return redirect()->route('pegawai.index')->with('message', 'Data berhasil dihapus!');
}
public function search(Request $request)
{
$q = $request->input('searchpegawai');
$pegawais = Pegawai::where('nama_pegawai', 'LIKE', '%'.$q.'%')
->orWhere('alamat', 'LIKE', '%'.$q.'%')
->paginate(5);
return view('pegawai.index')->with('pegawais', $pegawais)->with('query', $q);
}
}
Here Is The Index blade where the search function are...
index.blade.php
#extends('template.adminlte')
#section('content')
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<div class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0 text-dark">Menu Pegawai</h1>
</div><!-- /.col -->
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item active">pegawai</li>
</ol>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container-fluid -->
</div>
<a href="{{ route('pegawai.create') }}" class="btn btn-info btnsm float-left">
<i class="fas fa-plus-circle"> Tambah Pegawai</i>
</a><br><br>
<form class="form-inline ml-3 float-sm-right">
<form action="searchpegawai" method="GET" role="Search" class="form-inline ml-3">
<div class="input-group input-group-sm float-sm-right">
<input class="form-control form-control-navbar float-sm-right" type="search" placeholder="Search" aria-label="Search" name=searchpegawai>
<div class="input-group-append float-sm-right">
<button class="btn btn-navbar" type="submit">
<i class="fas fa-search"></i>
</button>
</div>
</div>
</form>
#if ($message = Session::get('message'))
<div class="alert alert-success martop-sm">
<p>{{ $message }}</p>
</div>
#endif
<table class="table martop-sm">
<thead>
<th>No</th>
<!-- <th>ID</th> -->
<th>Kategori</th>
<th>Jabatan Pegawai</th>
<th>Nama pegawai</th>
<th>Alamat</th>
<th>Foto Pegawai</th>
<th>Aksi</th>
</thead>
<tbody>
#foreach ($pegawais as $key => $pegawai)
<tr>
<td>{{ $pegawais->firstItem() + $key }}</td>
<!-- <td>{{ $pegawai->id }}</td> -->
<td>{{ $pegawai->kategori }}</td>
<td>{{ $pegawai->jabatan }}</td>
<td>{{ $pegawai->nama_pegawai }}</td>
<td>{{ $pegawai->alamat }}</td>
<td><img src="{{ asset('storage/images/' . $pegawai->gambar_pegawai) }}" alt="" width="100"></td>
<td>
<form action="{{ route('pegawai.destroy', $pegawai->id) }}" method="post">
{{csrf_field()}} {{ method_field('DELETE') }}
Ubah
<button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Apakah anda yakin ingin menghapusnya?');">Hapus</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
{{ $pegawais -> links() }}
</div>
</section>
</div>
#endsection

use forelse in blade
#forelse($pegawais as $key => $pegawai)
<tr>
<td>{{ $pegawais->firstItem() + $key }}</td>
<!-- <td>{{ $pegawai->id }}</td> -->
<td>{{ $pegawai->kategori }}</td>
<td>{{ $pegawai->jabatan }}</td>
<td>{{ $pegawai->nama_pegawai }}</td>
<td>{{ $pegawai->alamat }}</td>
<td><img src="{{ asset('storage/images/' . $pegawai->gambar_pegawai) }}" alt="" width="100"></td>
<td>
<form action="{{ route('pegawai.destroy', $pegawai->id) }}" method="post">
{{csrf_field()}} {{ method_field('DELETE') }}
Ubah
<button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Apakah anda yakin ingin menghapusnya?');">Hapus</button>
</form>
</td>
</tr>
#empty
<tr><td align="center" >Result not found.</td></tr>
#endforelse
ref link https://laravel.com/docs/8.x/blade#loops

Related

Why is the content of the tag and category button not visible when creating a post in laravel?

I try to create blog web page in laravel. While creating the post, the contents of the tag and category button are not visible.
My post.blade.php;
#extends('admin.layouts.app')
#section('headSection')
<link rel="stylesheet" href="{{ asset('admin/plugins/select2/select2.min.css') }}">
#endsection
#section('main-content')
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Text Editors
<small>Advanced form element</small>
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-dashboard"></i> Home</li>
<li>Forms</li>
<li class="active">Editors</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Titles</h3>
</div>
#include('includes.messages')
<!-- /.box-header -->
<!-- form start -->
<form role="form" action="{{ route('post.store') }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="box-body">
<div class="col-lg-6">
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Title">
</div>
<div class="form-group">
<label for="subtitle">Post Sub Title</label>
<input type="text" class="form-control" id="subtitle" name="subtitle" placeholder="Sub Title">
</div>
<div class="form-group">
<label for="slug">Post Slug</label>
<input type="text" class="form-control" id="slug" name="slug" placeholder="Slug">
</div>
</div>
<div class="col-lg-6">
<br>
<div class="form-group">
<div class="pull-right">
<label for="image">File input</label>
<input type="file" name="image" id="image">
</div>
<div class="checkbox pull-left">
<label>
<input type="checkbox" name="status" value="1"> Publish
</label>
</div>
</div>
<br>
<div class="form-group" style="margin-top:18px;">
<label>Select Tags</label>
<select class="form-control select2 select2-hidden-accessible" multiple="" data-placeholder="Select a State" style="width: 100%;" tabindex="-1" aria-hidden="true" name="tags[]">
#foreach ($tags as $tag)
<option value="{{ $tag->id }}">{{ $tag->name }}</option>
#endforeach
</select>
</div>
<div class="form-group" style="margin-top:18px;">
<label>Select Category</label>
<select class="form-control select2 select2-hidden-accessible" multiple="" data-placeholder="Select a State" style="width: 100%;" tabindex="-1" aria-hidden="true" name="categories[]">
#foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box">
<div class="box-header">
<h3 class="box-title">Write Post Body Here
<small>Simple and fast</small>
</h3>
<!-- tools box -->
<div class="pull-right box-tools">
<button type="button" class="btn btn-default btn-sm" data-widget="collapse" data-toggle="tooltip" title="Collapse">
<i class="fa fa-minus"></i></button>
</div>
<!-- /. tools -->
</div>
<!-- /.box-header -->
<div class="box-body pad">
<textarea name="body" style="width: 100%; height: 500px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;" id="editor1"></textarea>
</div>
</div>
<div class="box-footer">
<input type="submit" class="btn btn-primary">
Back
</div>
</form>
</div>
<!-- /.box -->
</div>
<!-- /.col-->
</div>
<!-- ./row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
#endsection
#section('footerSection')
<script src="{{ asset('admin/plugins/select2/select2.full.min.js') }}"></script>
<script src="{{ asset('admin/ckeditor/ckeditor.js') }}"></script>
<script>
$(function () {
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace('editor1');
});
</script>
<script>
$(document).ready(function() {
$(".select2").select2();
});
</script>
#endsection
I am stuck because everytime I submit a post with tags and category.
My edit blade.php file;
#extends('admin.layouts.app')
#section('headSection')
<link rel="stylesheet" href="{{ asset('admin/plugins/select2/select2.min.css') }}">
#endsection
#section('main-content')
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Text Editors
<small>Advanced form element</small>
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-dashboard"></i> Home</li>
<li>Forms</li>
<li class="active">Editors</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Titles</h3>
</div>
#include('includes.messages')
<!-- /.box-header -->
<!-- form start -->
<form role="form" action="{{ route('post.update',$post->id) }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<div class="box-body">
<div class="col-lg-6">
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Title" value="{{ $post->title }}">
</div>
<div class="form-group">
<label for="subtitle">Post Sub Title</label>
<input type="text" class="form-control" id="subtitle" name="subtitle" placeholder="Sub Title" value="{{ $post->subtitle }}">
</div>
<div class="form-group">
<label for="slug">Post Slug</label>
<input type="text" class="form-control" id="slug" name="slug" placeholder="Slug" value="{{ $post->slug }}">
</div>
</div>
<div class="col-lg-6">
<br>
<div class="form-group">
<div class="pull-right">
<label for="image">File input</label>
<input type="file" name="image" id="image">
</div>
<div class="checkbox pull-left">
<label>
<input type="checkbox" name="status" value="1" #if ($post->status == 1)
{{'checked'}}
#endif> Publish
</label>
</div>
</div>
<br>
<div class="form-group" style="margin-top:18px;">
<label>Select Tags</label>
<select class="form-control select2 select2-hidden-accessible" multiple="" data-placeholder="Select a State" style="width: 100%;" tabindex="-1" aria-hidden="true" name="tags[]">
#foreach ($tags as $tag)
<option value="{{ $tag->id }}"
#foreach ($post->tags as $postTag)
#if ($postTag->id == $tag->id)
selected
#endif
#endforeach
>{{ $tag->name }}</option>
#endforeach
</select>
</div>
<div class="form-group" style="margin-top:18px;">
<label>Select Category</label>
<select class="form-control select2 select2-hidden-accessible" multiple="" data-placeholder="Select a State" style="width: 100%;" tabindex="-1" aria-hidden="true" name="categories[]">
#foreach ($categories as $category)
<option value="{{ $category->id }}"
#foreach ($post->categories as $postCategory)
#if ($postCategory->id == $category->id)
selected
#endif
#endforeach
>{{ $category->name }}</option>
#endforeach
</select>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box">
<div class="box-header">
<h3 class="box-title">Write Post Body Here
<small>Simple and fast</small>
</h3>
<!-- tools box -->
<div class="pull-right box-tools">
<button type="button" class="btn btn-default btn-sm" data-widget="collapse" data-toggle="tooltip" title="Collapse">
<i class="fa fa-minus"></i></button>
</div>
<!-- /. tools -->
</div>
<!-- /.box-header -->
<div class="box-body pad">
<textarea name="body" style="width: 100%; height: 500px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;" id="editor1">{{ $post->body }}</textarea>
</div>
</div>
<div class="box-footer">
<input type="submit" class="btn btn-primary">
Back
</div>
</form>
</div>
<!-- /.box -->
</div>
<!-- /.col-->
</div>
<!-- ./row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
#endsection
#section('footerSection')
<script src="{{ asset('admin/plugins/select2/select2.full.min.js') }}"></script>
<script src="{{ asset('admin/ckeditor/ckeditor.js') }}"></script>
<script>
$(function () {
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace('editor1');
//bootstrap WYSIHTML5 - text editor
$(".textarea").wysihtml5();
});
</script>
<script>
$(document).ready(function() {
$(".select2").select2();
});
</script>
#endsection
My show blade php file;
#extends('admin.layouts.app')
#section('headSection')
<link rel="stylesheet" href="{{ asset('admin/plugins/datatables/dataTables.bootstrap.css') }}">
#endsection
#section('main-content')
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Blank page
<small>it all starts here</small>
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-dashboard"></i> Home</li>
<li>Examples</li>
<li class="active">Blank page</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<!-- Default box -->
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Title</h3>
<a class='col-lg-offset-5 btn btn-success' href="{{ route('post.create') }}">Add New</a>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse">
<i class="fa fa-minus"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">
<i class="fa fa-times"></i></button>
</div>
</div>
<div class="box-body">
<div class="box">
<div class="box-header">
<h3 class="box-title">Data Table With Full Features</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>S.No</th>
<th>Title</th>
<th>Sub Title</th>
<th>Slug</th>
<th>Creatd At</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
#foreach ($posts as $post)
<tr>
<td>{{ $loop->index + 1 }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->subtitle }}</td>
<td>{{ $post->slug }}</td>
<td>{{ $post->created_at }}</td>
<td><span class="glyphicon glyphicon-edit"></span></td>
<td>
<form id="delete-form-{{ $post->id }}" method="post" action="{{ route('post.destroy',$post->id) }}" style="display: none">
{{ csrf_field() }}
{{ method_field('DELETE') }}
</form>
<a href="" onclick="
if(confirm('Are you sure, You Want to delete this?'))
{
event.preventDefault();
document.getElementById('delete-form-{{ $post->id }}').submit();
}
else{
event.preventDefault();
}" ><span class="glyphicon glyphicon-trash"></span></a>
</td>
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th>S.No</th>
<th>Title</th>
<th>Sub Title</th>
<th>Slug</th>
<th>Creatd At</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
Footer
</div>
<!-- /.box-footer-->
</div>
<!-- /.box -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
#endsection
#section('footerSection')
<script src="{{ asset('admin/plugins/datatables/jquery.dataTables.min.js') }}"></script>
<script src="{{ asset('admin/plugins/datatables/dataTables.bootstrap.min.js') }}"></script>
<script>
$(function () {
$("#example1").DataTable();
});
</script>
#endsection
My PostController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Model\user\category;
use App\Model\user\post;
use App\Model\user\tag;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = post::all();
return view('admin.post.show',compact('posts'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$tags =tag::all();
$categories =category::all();
return view('admin.post.post',compact('tags','categories'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
return $request->all();
$this->validate($request,[
'title'=>'required',
'subtitle'=>'required',
'slug'=>'required',
'body'=>'required',
]);
$post = new post;
$post->title = $request->title;
$post->subtitle = $request->subtitle;
$post->slug = $request->slug;
$post->body = $request->body;
$post->status = $request->status;
$post->save();
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);
return redirect(route('post.index'));
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$post= post::where('id',$id)->first();
$tags =tag::all();
$categories =category::all();
return view('admin.post.edit',compact('tags','categories','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',
'subtitle'=>'required',
'slug'=>'required',
'body'=>'required',
]);
$post = post::find($id);
$post->title = $request->title;
$post->subtitle = $request->subtitle;
$post->slug = $request->slug;
$post->body = $request->body;
$post->status = $request->status;
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);
$post->save();
return redirect(route('post.index'));
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
post::where('id',$id)->delete();
return redirect()->back();
}
}
My tagcontroller.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Model\user\tag;
use Illuminate\Http\Request;
class TagController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$tags = tag::all();
return view('admin.tag.show',compact('tags'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.tag.tag');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required',
'slug' => 'required',
]);
$tag = new tag;
$tag->name = $request->name;
$tag->slug = $request->slug;
$tag->save();
return redirect(route('tag.index'));
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$tag= tag::where('id',$id)->first();
return view('admin.tag.edit',compact('tag'));
}
/**
* 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',
'slug' => 'required',
]);
$tag = tag::find($id);
$tag->name = $request->name;
$tag->slug = $request->slug;
$tag->save();
return redirect(route('tag.index'));
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
tag::where('id',$id)->delete();
return redirect()->back();
}
}
My categorycontroller.php;
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Model\user\category;
use Illuminate\Http\Request;
class CategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$categories = category::all();
return view('admin.category.show',compact('categories'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.category.category');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required',
'slug' => 'required',
]);
$category = new category;
$category->name = $request->name;
$category->slug = $request->slug;
$category->save();
return redirect(route('category.index'));
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$category= category::where('id',$id)->first();
return view('admin.category.edit',compact('category'));
}
/**
* 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',
'slug' => 'required',
]);
$category = category::find($id);
$category->name = $request->name;
$category->slug = $request->slug;
$category->save();
return redirect(route('category.index'));
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
category::where('id',$id)->delete();
return redirect()->back();
}
}
How can I resolve this issue? And furthermore how can i do it?

Sorting and searching a foreign entity field on a Laravel Livewire table

I’ve just implemented a Livewire data table based on the Caleb’s tutorial on Laracasts. Everything works as expected when working with just one model. However I’m stuck trying to apply sorting and searching to a foreign model field.
User model:
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use Notifiable;
use HasRoles;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the user's email verified status.
*
* #param string $value
* #return string
*/
public function getEmailVerifiedAtAttribute($value)
{
if ($value == null) {
return "No";
}
return $value;
}
public function getRoleAttribute()
{
if($this->roles()->count() > 0) {
return $this->roles()->first()->name;
} else {
return "Usuario registrado";
}
}
public static function search($query)
{
return empty($query) ? static::query()
: static::where('name', 'like', '%'.$query.'%')
->orWhere('email', 'like', '%'.$query.'%');
}
}
Tried adding another orWhere() clause to the search() method in some ways. None worked. Now I left just the default ones.
Livewire controller:
namespace App\Http\Livewire\Users;
use Livewire\Component;
use Livewire\WithPagination;
class Table extends Component
{
use WithPagination;
public $perPage;
public $sortField;
public $sortAsc;
public $search;
public function mount()
{
$this->perPage = 10;
$this->sortField = 'name';
$this->sortAsc = true;
$this->search = '';
}
public function sortBy($field)
{
if ($this->sortField === $field) {
$this->sortAsc = ! $this->sortAsc;
} else {
$this->sortAsc = true;
}
$this->sortField = $field;
}
public function updatingPerPage()
{
$this->resetPage();
}
public function render()
{
return view('livewire.users.table', [
'users' => \App\User::search($this->search)
->with('roles')
->orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')
->paginate($this->perPage),
]);
}
}
Livewire view:
<div>
<div class="row mb-4">
<div class="col form-inline">
Mostrar
<select wire:model="perPage" class="form-control form-control-sm custom-select custom-select-sm">
<option>10</option>
<option>100</option>
<option>1000</option>
</select>
registros
</div>
<div class="col-sm-3">
<input wire:model="search" class="form-control form-control-sm" type="text" placeholder="Buscar usuarios...">
</div>
</div>
<div class="table-responsive mb-4" >
<div class="table-header">
<table class="table table-sm text-nowrap" role="grid">
<thead>
<tr>
<th width="30%">
<a wire:click.prevent="sortBy('name')" role="button" href="#">
Nombre
#include('partials._sort-icon', ['field' => 'name'])
</a>
</th>
<th width="30%">
<a wire:click.prevent="sortBy('email')" role="button" href="#">
Correo electrónico
#include('partials._sort-icon', ['field' => 'email'])
</a>
</th>
<th width="30%">
<a wire:click.prevent="sortBy('')" role="button" href="#">
Rol
#include('partials._sort-icon', ['field' => ''])
</a>
</th>
<th></th>
</tr>
</thead>
</table>
</div>
<div class="table-body">
<table class="table table-sm table-hover text-nowrap" role="grid">
<tbody>
#foreach ($users as $user)
<tr>
<td width="30%">{{ $user->name }}</td>
<td width="30%">{{ $user->email }}</td>
<td width="30%">{{ $user->role }}</td>
<td>
<form method="POST" action="{!! route('backend.users.user.destroy', $user->id) !!}" accept-charset="UTF-8">
<input name="_method" value="DELETE" type="hidden">
{{ csrf_field() }}
<div class="btn-group btn-group-xs float-right" role="group">
#can('users.show')
<a href="{{ route('backend.users.user.show', $user->id ) }}" class="btn btn-outline-default btn-xs" title="{{ trans('users.show') }}">
<i class=" fas fa-fw fa-eye" aria-hidden="true"></i>
</a>
#endcan
#can('users.edit')
<a href="{{ route('backend.users.user.edit', $user->id ) }}" class="btn btn-outline-default btn-xs" title="{{ trans('users.edit') }}">
<i class=" fas fa-fw fa-pencil-alt" aria-hidden="true"></i>
</a>
#endcan
#can('users.destroy')
<button type="submit" class="btn btn-outline-default btn-xs" title="{{ trans('users.delete') }}" onclick="return confirm("{{ trans('users.confirm_delete') }}")">
<i class=" fas fa-fw fa-trash-alt" aria-hidden="true"></i>
</button>
#endcan
</div>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
<div class="table-footer">
<div class="text-muted">
Showing {{ $users->firstItem() }} to {{ $users->lastItem() }} out of {{ $users->total() }} results
</div>
<div>
{{ $users->links() }}
</div>
</div>
</div>
Tried also some ways to pass an argument to the sortBy() and [‘field’ => ‘’] on the role column. Now I left them with empty strings.
I know, this issue probably is more related to Laravel than Livewire, but I’ll really appreciate any help.
Update:
Solved using the Laravel Query Builder instead of Eloquent.

Missing required parameters for [Route: berita.update]

I'm trying to get the parameter id_berita, it appears in url, but when i want to show the previous data it can't....
Controller
class KontenController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:admin');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$berita = Berita::all();
return view('backpages/berita', compact('berita'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('backpages.berita_input'); //untuk menampilkan form add
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
request()->validate([
'id_berita' => 'required',
'id_kategori' => 'required',
'username' => 'required',
'tanggal' => 'required',
'judul' => 'required',
'isi' => 'required',
]);
Berita::create($request->all());
$request->session()->flash('pesan','Berita '.$request['id_berita'].' berhasil disimpan.');
return redirect()->route('berita.index');
}
/**
* Display the specified resource.
*
* #param \App\Berita $berita
* #return \Illuminate\Http\Response
*/
public function show(Berita $berita)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Berita $berita
* #return \Illuminate\Http\Response
*/
public function edit(Berita $berita)
{
// return view('backpages.berita_edit',compact('berita'));
$berita = Berita::find($berita);
// return view('backpages.berita_edit')->with('berita',$berita);
return view('backpages.berita_edit')->with('berita', $berita);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Berita $berita
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Berita $berita)
{
request()->validate([
'username' => 'required',
'tanggal' => 'required',
'judul' => 'required',
'isi' => 'required',
]);
$berita->update($request->all());
$request->session()->flash('pesan','Berita '.$request['judul'].' berhasil
diperbarui.');
return redirect()->route('berita.index');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Berita $berita
* #return \Illuminate\Http\Response
*/
public function destroy(Berita $berita)
{
//
}
}
berita_edit.blade.php for update process
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Edit Berita</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form action="{{route('berita.update')}}" method="POST">
{{ csrf_field() }}
{{method_field('PUT')}}
<div class="card-body">
<div class="form-group">
<label for="exampleInputPassword1">Username</label>
<input type="text" class="form-control" name="username" placeholder="Username" value="{{ $berita->username }}">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Tanggal</label>
<input type="date" class="form-control" name="tanggal" placeholder="Tanggal" value="{{ $berita->tanggal }}">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Judul</label>
<input type="text" class="form-control" name="judul" placeholder="Judul" value="{{ $berita->judul }}">
</div>
<div class="form-group">
<label>Isi</label>
<textarea class="form-control" rows="3" name="isi" value="{{ $berita->isi }}" placeholder="Enter ..."></textarea>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
For displaying data
<div class="card-body table-responsive p-0">
<table class="table table-hover text-nowrap">
<thead>
<tr>
<th>id_Berita</th>
<th>id_Kategori</th>
<th>Username</th>
<th>Tanggal</th>
<th>Judul</th>
<th>Isi</th>
<th colspan="2" style="text-align:left">Opsi</th>
</tr>
</thead>
<tbody>
#foreach($berita as $data)
<tr>
<td>{{$data -> id_berita}}</td>
<td>{{$data -> id_kategori}}</td>
<td>{{$data -> username}}</td>
<td>{{$data -> tanggal}}</td>
<td>{{$data -> judul}}</td>
<td>{{$data -> isi}}</td>
<td>
<a class="btn btn-block btn-info" href="{{ route('berita.edit', $data -> id_berita) }}"?>Edit</a>
</td>
<td>
<a class="btn btn-block btn-info" href="#"?>Hapus</a>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
You have to change action like this
<form action="{{route('berita.update',['berita'=>$berita->id])}}" method="POST">
<a class="btn btn-block btn-info" href="{{ route('berita.edit', ['berita'=>$data->id_berita]) }}"?>Edit</a>

How to retrive data from DB and display it in a responding navigation menu?

I am using laravel 5.3
I have a form that helps me create new projects. I can also display all the projects I have in DB with all the attributes.
Now, I need to display responding navigation menu in the left on the page that contains the following :
Domaines :
Domaine 1 :
project 1
project 2
Domaine 2 :
project A
project B
I want that once I click on project there's table that display all the information of that project.
this is "index.blade.php" when I only was trying to display the projects without any ordre :
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Projects CRUD</h2>
</div>
<div class="pull-right">
#permission('pro-create')
<a class="btn btn-success" href="{{ route('pros.create') }}"> Create New Project</a>
#endpermission
</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>title</th>
<th>code</th>
<th>domain_id</th>
<th width="280px">Action</th>
</tr>
#foreach ($pros as $key => $pro)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $pro->title }}</td>
<td>{{ $pro->code }}</td>
<td>{{ $pro->domain_id}}</td>
<td>
<a class="btn btn-info" href="{{ route('pros.show',$pro->id) }}">Show</a>
#permission('pro-edit')
<a class="btn btn-primary" href="{{ route('pros.edit',$pro->id) }}">Edit</a>
#endpermission
#permission('pro-delete')
{!! Form::open(['method' => 'DELETE','route' => ['pros.destroy', $pro->id],'style'=>'display:inline']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
#endpermission
</td>
</tr>
#endforeach
</table>
{!! $pros->render() !!}
#endsection
and this is what I was trying to add to have the "responding navigation menu" :
<div class="nav-side-menu">
<div class="brand">Menu</div>
<i class="fa fa-bars fa-2x toggle-btn" data-toggle="collapse" data-target="#menu-content"></i>
<div class="menu-list">
<ul id="menu-content" class="menu-content collapse out">
<li>
<a href="#">
<i class="fa fa-dashboard fa-lg"></i> Dashboard
</a>
</li>
<li data-toggle="collapse" data-target="#domains" class="collapsed active">
<i class="fa fa-gift fa-lg"></i> Domains <span class="arrow"></span>
</li>
<ul class="sub-menu collapse" id="domains">
<li class="active">Domain 1</li>
<li>Domain 2</li>
<li>Domain 3</li>
<li>Domain 4</li>
<li>Domain 5</li>
</ul>
<li data-toggle="collapse" data-target="#responsible" class="collapsed">
<i class="fa fa-globe fa-lg"></i> Responsibles <span class="arrow"></span>
</li>
<ul class="sub-menu collapse" id="responsible">
<li>Mr.name1</li>
<li>Mr.name2</li>
<li>Mr.name3</li>
</ul>
</div>
</div>
My question is how to build a relation between my DB and the view? how can I retrieve data from DB (projects table) and display it in the view ?
You create a model for your table "Example"
Model
class Example extends Model {
protected $table = 'Example';
protected $fillable = ['column1', 'column2'];
protected $primaryKey = 'id';
}
Don't forget to specify your connection in /config/database.php
Now you have your model you can create a Controller, I would suggest a resource controller.
use App\Model\Example;
class ExampleController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
// This is the one we need, because it will be shown on GET domain.com/example
$examples = Example::query()->get();
return view('exampleview', ['passed_data' => $examples]);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
Define your route. Because you want to display frontend you choose routes/web.php and define
Route::resource('example', 'ExampleController');
Now you also have to make your blade under resources\views called exampleview.blade.php (as defined in the controller)
there you can use the passed data in blade syntax:
exampleview.blade.php
#foreach ($passed_data as $single_example)
{{ $example }}
#endforeach
To make your menu change based on the view you are in you should define a
#stack('menustack') inside your menu blade
and push new element from the "lower" blade with
#push('menustack')
<div> new menu div </div>
#endpush
You need to create nav.php in app/Http directory like:
app/Http/nav.php
<?php
//pass your view file path like *index*
View::composer('index', function($view){
//For navigation menu items...
$navigation = DB::table('navigation')
->select('Domain1', 'Domain2', 'Domain3', 'Domain4', 'Domain5')
->get();
return $view->with('navigations' => $navigations);
});
?>
And define nav.php route in routes/web like:
// For navigation menu route
**require 'nav.php';**
Hope this works for you!

symfony2 update entity out of modal

almost whole night I'm trying to update an entity with a form in a modal, but it doesn't work...
My twig template looks like :
{% for entity in entities %}
<tr>
<td class="text-center">{{ entity.id }}</td>
<td class="text-center">{{ entity.cashbackDays }} Tage</td>
<td class="text-center">{{ entity.cashbackPercent }} %</td>
<td class="text-center">{{ entity.nettoDays }} Tage</td>
<td class="text-center">
<a data-toggle="modal" data-target="#editCashbackModal" class="btn btn-xs btn-default" href="{{ path('cashback_edit', { 'id': entity.id }) }}"><i
class="fa fa-edit"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
<div class="modal fade" id="editCashBackModal" tabindex="-1" role="dialog" aria-labelledby="editCashBackModalLabel" aria-hidden="true">
</div>
the modal template looks like:
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title" id="editCashBackModalLabel">Skontoschlüssel bearbeiten</h4>
</div>
<div class="modal-body">
{{ form(edit_form) }}
<ul class="record_actions">
<li>
<a href="{{ path('cashback') }}">
Back to the list
</a>
</li>
<li>{{ form(delete_form) }}</li>
</ul>
</div>
<div class="modal-footer">
</div>
</div>
</div>
I think I got problems with the variable in the URl but I don't know how to fix it.
This is the part of my controller:
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('sulzerAppBundle:Cashback')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Cashback entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a Cashback entity.
*
* #param Cashback $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Cashback $entity)
{
$form = $this->createForm(new CashbackType(), $entity, array(
'action' => $this->generateUrl('cashback_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
The Error is that the modal doesn't open at click on edit
You have to add form submission:
protected $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('sulzerAppBundle:Cashback')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Cashback entity.');
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
$editForm->handleRequest($this->requestStack);
if ($editForm->isSubmitted() && $editForm->isValid()) {
/** #var Cashback $cashback */
$cashback = $editForm->getData();
...
$em->persist($cashback);
$em->flush();
}
...
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
Read more about forms and symfony 2.7 demo

Resources