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

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!

Related

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

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

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.

Is there any way to get an id in a create method in laravel

I am trying to pass a foreign directly to my create method
In the project I am working on, I have two different users. The first one is a farm who can create an animal
The second one is the clinic who can attach to an animal some clinic details showing if the animal was vaccinated or not. In my clinic details table, I have the animal as a foreign key but I do not know how I will pass that key to the create method
Here is my Clinic controller
<?php
namespace App\Http\Controllers;
use App\Animal;
use App\Clinic;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ClinicController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$user = Auth::user();
$animal = Animal::all();
return view('clinic.index', compact('user', 'animal'));
}
/**
* Show the form for creating a new resource.
*
* #param $id
* #return void
*/
public function create($id)
{
$user = Auth::user();
$animal = Animal::query()->findOrFail($id);
$clinic = new Clinic();
return view('clinic/create', compact('user', 'animal', 'clinic'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$animal = Animal::query()->findOrFail($id);
return view('clinic.show', compact('animal'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
My clinic index.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header"><h3>Clinic Details Dashboard</h3></div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
You are logged in! {{ $user->name}}
<hr>
<center><h3>Animals</h3></center>
<hr>
#foreach($animal as $animal)
<div class="row">
<div class="col-2">{{ $animal->id }}</div>
<div class="col-4">{{ $animal->type->category }}</div>
<div class="col-2">{{ $animal->user->name }}</div>
<div class="col-4">{{ $animal->created_at }}</div>
</div>
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
my clinic show.blade.php
This is where I would like to pass the animal id to the create method but I do not know how.
Even my button link is not going to the create view
#extends('layouts.app')
#section('title', 'Details for animal ')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<center><h3>Details for the animal</h3></center>
</div>
<div class="card-body">
<div class="col-12">
<p><strong>Id: </strong>{{ $animal->id }}</p>
<p><strong>Animal: </strong>{{ $animal->type->category }}</p>
<p><strong>Farm: </strong>{{ $animal->user->name }}</p>
<p><strong>Gender: </strong>{{ $animal->gender }}</p>
<p><strong>Place Of Birth: </strong>{{ $animal->placeOfBirth }}</p>
<p><strong>Date: </strong>{{ $animal->created_at }}</p>
</div>
<div class="col-md-8 offset-md-4">
<a href="create">
<button type="button" class="btn btn-primary">
Attach Clinic Detail
</button>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
clinic create.blade.php
This view is still somehow empty
#extends('layouts.app')
#section('title', 'Add Clinical Details')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">New Animal</div>
<div class="card-body">
<form action="{{ url('clinic') }}" method="POST">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
You could simply add a parameter to your method like this:
public function create($id, $foreignKeyId) {
// ... to something
}
For that you would need to pass id as a hidden input.
You could also try to create a relation, that way you do not need to add the foreignKey as a parameter. You could simply access the foreign_key using the specified ORM Model.
You can use insertGetId() method for retrieving last created id after store method.
https://laravel.com/api/5.0/Illuminate/Database/Query/Builder.html#method_insertGetId
$id = DB::table('posts')->insertGetId(
array('title' => 'my post title', 'body' => 'my post body')
);

Display data in a treeviewDisplay data in a treeview

I'm Working on Laravel.
I'm trying to display my data in a treeview. But i success only the first step. Someone of you can help please ?
DataBase Structure
My achievement
Code:
<button class=" btn-primary" type="button" data-toggle="collapse" data-target=".multi-collapse" aria-expanded="false" aria-controls=".multi-collapse" >
<span class="glyphicon glyphicon-eye-open"></span></button>
#foreach(App\Account::where('nomencloture', 'LIKE', '_')->get() as $item)
<div class="collapse multi-collapse" id="{{$item->nomencloture}}" >
<div class="list-group-item " >
<div class="col-md-2"> {{ $item->account_id }}</div>
<div class="col-md-2"> {{ $item->account_name }}</div>
<button class=" btn-primary" type="button" data-toggle="collapse" data-target="#PUT SOMETHINGHERE" aria-expanded="false" aria-controls="multiCollapseExample1" >
<span class="glyphicon glyphicon-eye-open"></span></button>
<br>
<br>
#foreach(App\Account::where('nomencloture', 'LIKE', '_______')->get() as $subitem)
<div class="collapse" id="{{ $subitem->nomencloture }}" >
<br>
<div class="list-group-item ">
<div class="col-md-2"> {{ $subitem->account_id }}</div>
<div class="col-md-2"> {{ $subitem->account_name }}</div>
</div>
</div>
#endforeach
</div>
</div>
#endforeach
You need to make some changes in your code, please find below step to change code
Step 1: Please create relations with your foreign key in your model file like
namespace App;
use Illuminate\Database\Eloquent\Model;
class Treeview extends Model
{
protected $table = 'treeview';
public $fillable = ['title','parent_id'];
/**
* Get the index name for the model.
*
* #return string
*/
public function childs() {
return $this->hasMany('App\Treeview','parent_id','id') ;
}
}
Step 2: Add below function in your controller and make some changes according to your table and model object
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function manageCategory()
{
$categories = Treeview::where('parent_id', '=', 0)->get();
return view('treeview/categoryTreeview',compact('categories')); // set the path of you templates file.
}
Step 3 : Add below code in your categoryTreeview templates file
<h3>Category List</h3>
<ul id="tree1">
#foreach($categories as $category)
<li>
{{ $category->title }}
#if(count($category->childs))
#include('treeview/manageChild',['childs' => $category->childs]) // Please create another templates file
#endif
</li>
#endforeach
</ul>
Step 4: Please Create another templates file manageChild add below code.
<ul>
#foreach($childs as $child)
<li>
{{ $child->title }}
#if(count($child->childs))
#include('treeview/manageChild',['childs' => $child->childs])
#endif
</li>
#endforeach
</ul>
Output displayed Like:
Category List
Cat_1
Cat_1_par_1
Cat_1_par_2
Cat_1_par_3
Cat_2
Cat_2_par_1
Cat_2_par_2
Cat_2_par_3
Cat_3
More information I found one link: https://itsolutionstuff.com/post/laravel-5-category-treeview-hierarchical-structure-example-with-demoexample.html

Laravel page not found at create function

Recently I started programming using Laravel as a framework. Everything goes fine, but I tried to write a create script with the following message at runtime:
Sorry, the page you are looking for could not be found.
That's after posting Accept in the Create form, I already have created Index, Show, Update and delete functions successfully. So the route to my controller is correct, the file exist ... I'm totally stuck and can not see what incorrect.
Please help.
I didn't redirect the public folder so I'm still using the full path with no problem at the other modules (/gymmgr/public/lockers).
I send you the code:
index.blade.php
#extends('layouts.app')
#section('content')
#guest
#else
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0">
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#">Lockers</a>
</nav>
<div class="container-fluid">
<div class="row">
<nav class="col-sm-1 d-md-block bg-light sidebar">
<div class="sidebar-sticky">
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Acciones</span>
<a class="d-flex align-items-center text-muted" href="#">
<span data-feather="plus-circle"></span>
</a>
</h6>
<ul class="nav flex-column">
<li class="nav-item">
<span data-feather="home"></span>
<span class="sr-only"></span>
</li>
<li class="nav-item">
<a class="nav-link" href="/gymmgr/public/lockers/create">
<span data-feather="file"></span>
Nuevo
</a>
</ul>
</div>
</nav>
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
<h1 class="h5">Catálogo</h1>
<div class="btn-toolbar mb-2 mb-md-0">
<div class="btn-group mr-2">
<button class="btn btn-sm btn-outline-secondary">Exportar</button>
</div>
</div>
</div>
<table class="table">
<thead class="thead-light">
<tr>
<th>Clave del locker</th>
<th>Ubicación</th>
</tr>
</thead>
<tbody>
#foreach($lockers as $locker)
<tr>
<td> {{ $locker->strClaveLocker }} ></td>
<td>{{ $locker->strUbicacion }}</td>
</tr>
#endforeach
</tbody>
</table>
</main>
</div>
</div>
#endguest
#endsection
LockersController.php
<?php
namespace App\Http\Controllers;
use App\Locker;
use Illuminate\Http\Request;
class LockersController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$lockers = Locker::all();
return view('lockers.index', ['lockers'=>$lockers]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view('lockers.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
/*
if (Auth::check())
{*/
$locker = Locker::create(
['strClaveLocker'=>$request->input('strClaveLocker'),
'strUbicacion'=>$request->input('strUbicacion')
]
);
if($locker)
{
return redirect()->route('lockers.index')->with('success','Locker creado con éxito');
}
// }*/
}
/**
* Display the specified resource.
*
* #param \App\Locker $locker
* #return \Illuminate\Http\Response
*/
public function show(Locker $locker)
{
//
$locker = Locker::find($locker->idLocker);
//$locker = Locker::where('idLocker', $locker->idLocker)->first();
//echo e($locker->idLocker);
return view('lockers.show', ['locker'=>$locker]);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Locker $locker
* #return \Illuminate\Http\Response
*/
public function edit(Locker $locker)
{
//
$locker = Locker::find($locker->idLocker);
if ($locker)
{
return view('lockers.edit', ['locker'=>$locker])->with('success', 'Locker encontrado');
};
return view('lockers.edit', ['locker'=>$locker]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Locker $locker
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Locker $locker)
{
//
$lockerUpdate = Locker::where('idLocker', $locker->idLocker)->update([
'strClaveLocker'=>$request->input('strClaveLocker'),
'strUbicacion'=>$request->input('strUbicacion')]);
if ($lockerUpdate)
{
return redirect()->route('lockers.show',['lockers'=>$locker->idLocker])
->with('success', 'Locker actualizado correctamente');
}
return back()->withInput();
}
/**
* Remove the specified resource from storage.
*
* #param \App\Locker $locker
* #return \Illuminate\Http\Response
*/
public function destroy(Locker $locker)
{
//
$findLocker = Locker::find($locker->idLocker);
if($findLocker->delete())
{
return redirect()->route('lockers.index')
->with('success','Locker borrado exitosamente');
}
return back()->withInput()->with('error','El locker no pudo borrarse');
}
}
create.blade.php
#extends('layouts.app')
#section('content')
#guest
#else
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Locker') }}</div>
<div class="card-body">
</form>
<form method="post" action="{{ route('lockers.create') }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="put">
<div class="form-group">
<label for="locker-clave">Clave del locker<span class="required">*</span></label>
<input placeholder="Clave del locker"
id="locker-clave"
required
name="strClaveLocker"
spellcheck="false"
class="form-control"
/>
</div>
<div class="form-group">
<label for="locker-ubicacion">Ubicación del locker</label>
<input placeholder="Ubicación del locker"
id="locker-ubicacion"
required
name="strUbicacion"
class="form-control"
/>
</div>
<div class="form-group">
<input type="submit"
class="btn btn-primary"
value="Aceptar"
/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endguest
#endsection
The route
web.php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('lockers','LockersController');
Your create form has:
<form method="post" action="{{ route('lockers.create') }}">
...
<input type="hidden" name="_method" value="put">
So you are sending a PUT request to your create route. As the docs describe, the .create route the resource declaration sets up is expecting a GET (check the table of actions it sets up). So that request will fail with a 404 as there is no matching route set up.
Also, though confusingly named, the create route is for displaying the create form, not saving data you've entered into that form. So you should not be submitting data to your create route.
You need to:
Change your form action to point to your store route: ... action="{{ route('lockers.store') }}
Remove the form method spoofing, store expects POST which is what you'll get by default without any spoofing.

Resources