How to redirect on reference after admin login - laravel

I have to redirect the admin to /admin/reference instead of /admin/index.
I have changed the LoginController,protected $redirectTo = '/admin/reference';.t The same with RegisterController, the same with the VerificationController and the RedirectIfAuthenticated but still no redirection.
LoginController:
protected $redirectTo = '/admin/reference';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
RegisterController:
protected $redirectTo = '/admin/reference';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
VerificationController:
protected $redirectTo = '/admin/reference';
AdminController:
public function index()
{
return view('admin.index');
}
Authenticate Middleware:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
RedirectIfAuthenthicated:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/admin/reference');
}
return $next($request);
}
index.blade.php:
This is what is currently shows
#extends('admin.layouts.app')
#section('content')
Willkommen!
#endsection
admin.reference.index:This is what i want it to show
#extends('admin.layouts.app')
#section('title', '| Übersicht Referenzen')
#section('content')
<div class="row justify-content-center">
<div class="col-12">
<div class="panel panel-default">
<div class="panel-heading"><h3>Referenzen</h3></div>
<div class="panel-heading">Seite {{ $references->currentPage() }} von {{ $references->lastPage() }}</div>
<table class="table table-bordered table-striped">
<tr>
<th>Name</th>
<th>Bilder</th>
<th>Priorität</th>
<th>Aktionen</th>
</tr>
#foreach ($references as $reference)
<tr>
<td width="65%">
<a href="{{ route('admin.reference.edit', $reference->id ) }}"><b>{{ $reference->title }}</b>
</a><br>
</td>
<td>
#if(!count($reference->images))<span style="color:#ff0000;font-weight:700;">0</span>#else{{ count($reference->images) }}#endif
</td>
<td>
{{ $reference->priority }}
</td>
<td>
<a href="{{ route('admin.reference.edit', $reference->id) }}" class="btn btn-info pull-left"
style="margin-right: 3px; display: inline-block;">Edit</a>
<div style="display: inline-block;">
{!! Form::open(['method' => 'DELETE', 'route' => ['admin.reference.destroy', $reference->id], 'data-item-id' => $reference->id ]) !!}
{!! Form::submit('Löschen', ['class' => 'btn btn-danger delete-submit','data-item-id' => $reference->id]) !!}
{!! Form::close() !!}
</div>
</td>
</tr>
#endforeach
</table>
</div>
<div class="text-center">
{!! $references->links() !!}
</div>
</div>
</div>
#endsection
I expect after the login to be redirected to /admin/reference instead of /admin/index.

I'm working on laravel 5.5 but I think this would help you. Try adding this to your login controller
protected function authenticated(Request $request, $user)
{
if ( $user->isAdmin() ) {// check role
return redirect('/admin/reference');;
}
return redirect('/anywhere');
}

protected function authenticated()
{
if ( Auth::user() ) {
return redirect('/admin/reference');
}
return redirect('/');
}
added a protected function into my LoginController and it worked.

Related

Laravel 8: Attempt to read property "id" on null

I am facing this error 'Attempt to read property "id" on null' in Laravel 8. It was working fine before but in my view I changed $user->id to $user->profile->id and now this is happening. I am logged in the app and I have changed my route accordingly to match profile id, I have also tried clearing cache etc.
Here is my Code:
User Model:
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
// protected $fillable = [
// 'name',
// 'email',
// 'password',
// ];
protected $table = 'users';
protected $guarded = [];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
public function posts ()
{
return $this->hasMany(Post::class);
}
public function profile()
{
return $this->hasOne(Profile::class);
}
}
Profile Model:
class Profile extends Model
{
use HasFactory;
protected $table = 'profiles';
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
}
ProfilesController:
class ProfilesController extends Controller
{
public function show(User $user)
{
return view ('profiles.index', compact('user'));
}
public function edit(User $user)
{
return view ('profiles.index', compact('user'));
}
}
Route:
Route::get('profile/{profile}', [ProfilesController::class, 'show'])->middleware('auth');
Route::get('profile/{profile}/edit', [ProfilesController::class, 'edit'])->middleware('auth');
View:
<x-layout>
<section class="py-8 max-w-4xl mx-auto">
<h1 class="text-lg font-bold mb-8 pb-2 border-b">
#if ($user->id == auth()->user()->id)
Hello {{ $user->name }}, welcome to your profile.
#else
{{ $user->name }}'s Profile.
#endif
</h1>
<div class="flex">
<aside class="w-48 flex-shrink-0">
<h4 class="font-semibold mb-4">
Navigation
</h4>
<ul style="max-width: 75%">
<li>
View Profile
</li>
<li>
#if ($user->id == auth()->user()->id)
Edit Profile
#endif
</li>
</ul>
</aside>
<main class="flex-1">
<x-panel>
<div class="flex flex-col">
<div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
<div class="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
<div class="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
<div class="flex flex-row grid-cols-12">
<div class="flex flex-col col-span-4 row-span-full justify-items-start flex-grow-0 flex-shrink-0 grid-cols-4">
<div class="flex flex-row">
<img src="http://i.pravatar.cc/60?u={{ $user->profile->id }}" alt="" width="" height="" class="rounded-full h-24 w-24 flex m-2">
</div>
</div>
<div class="flex flex-col col-span-8 justify-right grid-cols-8 text-sm">
<div class="flex flex-row">
<div class="flex flex-col col-span-2 font-semibold">
<div class="pt-3">Name:</div>
<div class="pt-3">Email:</div>
<div class="pt-3">About:</div>
</div>
<div class="flex flex-col col-span-10">
<div class="pt-3 pl-4 text-justify">{{ $user->profile->name }}</div>
<div class="pt-3 pl-4 text-justify">{{ $user->profile->email }}</div>
<div class="pt-3 pl-4 text-justify"><p>{{ $user->profile->description }}</p></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</x-panel>
</main>
</div>
</section>
I think the problem is that you are passing a Profile model as indicated by your routes, but the method is looking for a User model.
Show and Edit have a User Model as a parameter. If you pass the Profile id, the method is gonna find the User model by id but with the id of the Profile model and not the user_id of the Profile model.
You will need to change the methods to:
public function show(Profile $profile)
{
$user = $profile->user;
return view ('profiles.index', compact('user'));
}
public function edit(Profile $profile)
{
$user = $profile->user;
return view ('profiles.index', compact('user'));
}
With this code the Profile model is found and via the relationship the User is obtained and passed to the view.
public function edit($id)
{
$table = Table::find($id);
return view('tables.edit', compact('table'));
}
public function update(Request $request, $id)
{
$table = Table::find($id);
$table->update($request->all());
return redirect('/tables');
}

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.

ErrorException thrown with message "Trying to get property 'subo_name' of non-object

ErrorException thrown with message
"Trying to get property 'subo_name' of non-object (View:
C:\xampp\htdocs\org\resources\views\users\index.blade.php)"
Main model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Maino extends Model
{
protected $fillable = [
'maino_name'
];
public function subo()
{
return $this->hasMany('App\Subo');
}
}
Sub model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subo extends Model
{
protected $fillable = [
'subo_name','maino_id'
];
public function maino()
{
return $this->belongsTo('App\Maino');
}
public function users()
{
return $this->hasMany('App\User');
}
}
user model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','role_id'
];
/**
* 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',
];
public function role()
{
return $this->belongsTo('App\Role');
}
public function profile()
{
return $this->hasMany('App\Profileinfo');
}
public function suborg()
{
return $this->belongsTo('App\Subo');
}
}
UserController code
public function index()
{
// $user=User::all();
$users=User::all();
return view('users.index',compact('users'));
}
index.blade.php
#extends('mainorg.main')
#section('title','Users')
#section('content')
<!-- DataTables Example -->
#if(Session::has('status'))
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span></button>
{{ Session::get('status') }}
</div>
#endif
<div class="card mb-3">
<div class="card-header">
<!-- <i class="fas fa-table"></i>
MainOrg --><div class="container"><button class="btn btn-primary float-right">Add SubOrg</button></div></div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>user</th>
<th>main org</th>
<th>suborg</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tfoot>
<tr>
<th>id</th>
<th>name</th>
<th>user</th>
<th>main org</th>
<th>suborg</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</tfoot>
#foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->role->role_name}}</td>
<td>{{$user->suborg->subo_name}}</td>
<td>Edit</td>
<td><form action="{{route('users.destroy',$user->id)}}" method="post">
#method('DELETE')
#csrf
<input type="submit" name="" value="DELETE" class="btn btn-danger">
</form></td>
</tr>
#endforeach
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
#endsection
I am facing problem regarding to this code so please help me solve this problem ......................
The error means that one of your $users doesn't have a suborg while looping. So {{ $user->suborg }} is null, and you can't access ->name of null. To handle this, restrict your users to only those that have a suborg, or check while looping:
public function index() {
$users=User::with('suborg')->has('suborg')->get();
return view('users.index',compact('users'));
}
Note: You can use both with and has in a single query; they do different things.
Or, while looping your users, check existence:
#foreach($users as $user)
<tr>
<td>
#if($user->suborg)
{{ $user->suborg->subo_name }}
#else
No Suborg
#endif
</td>
</tr>
#endforeach
When you creating relation between two or more models then you should use relational method during model use using with in your eloquent call, you can also write when you want to pass multiple like - with(['suborg', 'example']). In index method, bellow $users variable make dd($users) and check is there have any relational data. If found I think, it should work.
public function index()
{
// $user=User::all();
$users=User::with('suborg')->get();
return view('users.index',compact('users'));
}
And your index.blade.php
#foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->role->role_name}}</td>
<td>{{$user->suborg->subo_name || 'Not Found'}}</td>
......
#endforeach

Inserting data to related models

How to add a new data into related table ? I have two tables, the first is Edisi (Edition in English) table and Jurnal (Journal in English) table. The edisi table will contains many jurnal data, or in English the Edition table will contain many Journals data. My question is, how is the method create and save would look like ? I have created the function but it's not working.
Edisi table :
class CreateTableEdisi extends Migration
{
public function up()
{
Schema::create('edisi', function (Blueprint $table) {
$table->increments('id');
$table->string('judul')->unique();
$table->text('cover')->nullable();
$table->timestamps();
});
//Set FK di kolom id_edisi di table Jurnal
Schema::table('jurnal', function(Blueprint $table) {
$table->foreign('id_edisi')->references('id')->on('edisi')->onDelete('cascade')->onUpdate('cascade');
});
}
public function down()
{
Schema::table('jurnal', function(Blueprint $table) {
$table->dropForeign('jurnal_id_edisi_foreign');
});
Schema::drop('edisi');
}
}
Jurnal table :
class CreateTableJurnal extends Migration
{
public function up()
{
Schema::create('jurnal', function (Blueprint $table) {
$table->increments('id');
$table->string('judul', 200);
$table->string('penulis');
$table->text('abstrak');
$table->text('file');
$table->integer('id_edisi')->unsigned();
$table->timestamps();
});
}
public function down()
{
Schema::drop('jurnal');
}
}
Controller :
public function create()
{
return view('jurnal/create');
}
public function store(JurnalRequest $request)
{
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
//Insert data jurnal
$jurnal = Jurnal::create($input);
return redirect('jurnal');
}
Show View :
#extends('template')
#section('main')
<div class="container sitecontainer single-wrapper bgw">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 m22">
<div class="widget searchwidget joblist">
<div class="large-widget m30">
<div class="post row clearfix">
<div class="col-md-4">
<div class="post-media">
<img alt="" src="{{ asset('fotoupload/' . $edisi->cover) }}" class="img-responsive">
<a class="btn btn-primary btn-block">{{ $edisi->judul }}</a>
</div>
</div>
<div class="col-md-8">
<div id="siswa">
<h2>Daftar Jurnal</h2>
#if (count($jurnal_list) > 0)
<table class="table">
<thead>
<tr>
<th>Judul</th>
<th>Penulis</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($jurnal_list as $jurnal): ?>
<tr>
<td>{{ $jurnal->judul }}</td>
<td>{{ $jurnal->penulis }}</td>
<td>
<div class="box-button">
{{ link_to('jurnal/' . $jurnal->id, 'Detail', ['class' => 'btn btn-success btn-sm']) }}
</div>
<div class="box-button">
{{ link_to('jurnal/' . $jurnal->id . '/edit', 'Edit', ['class' => 'btn btn-warning btn-sm']) }}
</div>
<div class="box-button">
{!! Form::open(['method' => 'DELETE', 'action' => ['JurnalController#destroy', $jurnal->id]]) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger btn-sm']) !!}
{!! Form::close() !!}
</div>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
#else
<p>No Journals yet.</p>
#endif
<div class="tombol-nav">
Add new Journal to this edition
</div>
</div> <!-- / #jurnal -->
</div>
</div><!-- end post -->
</div><!-- end large-widget -->
</div><!-- end widget -->
</div><!-- end col -->
</div><!-- end row -->
</div><!-- end container -->
#stop
I'm new to Laravel and I'm stuck here. I tried everything I could (look at the controller) and when I try to add the journal data in the selected edition, it shows me error Constrains Fails. Thanks for your help!
First change $table->integer('id_edisi')->unsigned(); on your "jurnal" table to $table->integer('edisi_id')->unsigned();
Then add following method to "Jurnal" model
public function edisi()
{
return $this->belongsTo('App\Edisi');
}
if you don't like to change jurnal table as I showed earlier, modify above method as follows
public function edisi()
{
return $this->belongsTo('App\Edisi', 'id_edisi');
}
Then in controller
$jurnal_list = Jurnal::with('edisi')->get();
If you want to access "jurnal" from "edisi" add following method to the "Edisi" model
public function jurnals()
{
return $this->hasMany('App\Jurnal');
}
or for unmodified jurnals table.
public function jurnals()
{
return $this->hasMany('App\Jurnal', 'id_edisi');
}
Then in controller
$jurnal_list = Edisi::with('jurnals')->get();
Note: make sure to add $table variable to "Jurnal" and "Edisi" models, because normally table name needs be like s(ex:- Model: Post Table: posts, Model: Comment Table: comments)

Resources