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

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

Related

Undefined variable $statistic_teachers

I was trying to pass data to my view, but don't why there is a error
my blade which I want to pass data there
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">{{ __('StatistikAnsicht') }}</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<table id="statisticforteacher" class="table-responsive" style="width:100%">
<thead>
<th>FrageTitel</th>
<th>Kapitel</th>
<th>RichtigeRate</th>
</thead>
<tbody>
#foreach($statistic_teachers as $value)
<tr>
<td>{{$value -> question_title}}</td>
<td>{{$value -> chapters_id}}</td>
<td>{{$value -> correct_rate}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
and my controller, and use a connection with model to pass data
<?php
namespace App\Http\Controllers;
use App\Models\StatisticTeacher;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class StatisticTeacherController extends Controller
{
//
public function statisticteacher(){
$statistic_teachers = StatisticTeacher::all();
return view('statisticsA',compact('statistic_teachers'));
}
}
and this is my route, I think it isn't about my route, when I didn't pass data to the view, everythink works.
Route::get('/author_views.statisticsA', 'PagesController#getStatisticsAdmin')->name('statisticsA')->middleware('auth');
Route::get('/statisticsA', 'StatisticTeacherController#statisticteacher');
and this is model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class StatisticTeacher extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'id','question_title','chapters_id','correct_answer','wrong_ansers','correct_rate'
];
use HasFactory;
public $timestamps = false;
}
I think everything is ok, can not find such a syntax error, but it still doesn't work
can anyone help?
by the way this is stack trace
enter image description here
Please try below approach.
<?php
class StatisticTeacherController extends Controller
{
//
public function statisticteacher(){
$statistic_teachers = StatisticTeacher::all();
return view('statisticsA',['statistic_teachers' => $statistic_teachers]);
}
}
Check on which line in your blade file is throwing error. Compiled vies are stored inside storage\framework\views directory.

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.

Method Illuminate\Database\Eloquent\Collection::appends does not exist. I used kyslik/column-sortable package, sort and pagination are not working

Student Model
class Student extends Model
{
use Sortable;
protected $fillable = ['firstName', 'lastName', 'date', 'score', 'batch_id', 'subject_id', 'mark_id'];
public $sortable = [
'id', 'firstName', 'lastName', 'date', 'score', 'batch_id', 'subject_id', 'mark_id', 'created_at'
];
public function batch()
{
return $this->belongsTo('\App\Batch', 'batch_id');
}
public function subject()
{
return $this->belongsTo('\App\Subject', 'subject_id');
}
public function mark()
{
return $this->belongsTo('\App\Mark', 'mark_id');
}
public function role()
{
return $this->belongsTo('\App\Role', 'role_id');
}
}
Route
Route::get('/studentrecord', 'StudentController#sort');
Controller
public function sort()
{
$sort = Student::sortable()->paginate(5);
return view('/studentrecord', compact('sort'));
}
studentrecord.blade
<table class="table table-striped">
<thead>
<tr class="thead">
<th>#sortablelink('Exam Date')</th>
<th>#sortablelink('Student ID Number')</th>
<th>#sortablelink('Student Name')</th>
<th>#sortablelink('Batch')</th>
<th>#sortablelink('Subject')</th>
<th>#sortablelink('Results')</th>
<th>#sortablelink('Marks')</th>
<th>#sortablelink('Updated')</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#if($students->count())
#foreach($students as $student)
<tr class="tbody">
<td>{{$student->date}}</td>
<td>0001-00{{$student->id}}</td>
<td>{{$student->firstName.' '.$student->lastName}}</td>
<td>{{$student->batch->name}}</td>
<td>{{$student->subject->name}}</td>
<td>{{$student->score}}</td>
<td>{{$student->mark->name}}</td>
<td>{{$student->created_at->diffForHumans()}}</td>
<td>
<!-- View -->
#auth
#if(auth()->user()->role_id === 1)
<a href="/admin/editstudent/{{$student->id}}" class="btn btn-info form-control"><i
class="fa fa-edit" style="font-size:20px;color:#fff;"></i></a>
<form class="delete_form" action="/admin/removestudent/{{$student->id}}" method="POST">
#csrf
{{method_field("DELETE")}}
<button type="submit" class="btn btn-danger form-control">
<i class="fa fa-remove" style="font-size:20px;color:#fff;"></i>
</button>
</form>
#endif
#endauth
</td>
</tr>
#endforeach
#endif
</tbody>
</table>
<div>
{!! $students->appends(\Request::except('page'))->render() !!}
</div>
Laravel sort by descending or ascending with pagination.
if I clicked sort link it's not sorting but in url it changes to http://localhost:8000/studentrecord?sort=Batch&direction=asc and desc
please help me...thank you in advance
Instead of:
<th>#sortablelink('Student ID Number')</th>
Use this: <th>#sortablelink('id','Student ID Number')</th>
The first parameter of #sortablelink should be the column name in your database and the second parameter should be the name by which you want to display the column.
Do the same for all the table headings too.
Also, you need to add the following statement at the end of your table tag:-
</table>
{!! $students->appends(\Request::except('page'))->render() !!}
Here, div is not required.

How to redirect on reference after admin login

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.

Laravel 5. Error: my model with trashed and one relation.

Problem exists because transhed added, conflicted with tablerelation.
Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
public function category() {
return $this->hasOne('App\Models\Category', 'id', 'category_id');
}
}
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Category;
use App\Models\Post;
use Session;
use Auth;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = new Post();
// $allPosts = $posts::onlyTrashed()->get();
// $allPosts = $posts::withTrashed()->get();
$allPosts = $posts::all();
$postDeleted = $posts::onlyTrashed()->count();
return view('admin.post.index', ['posts' => $allPosts, 'postDeleted' => $postDeleted]);
}
...
View:
#foreach ($posts as $post)
<tr class="table-pages-list-item">
<td><input type="checkbox"></td>
<td>{{ $post->h1 }}</td>
<td>{{ $post->url }}</td>
<td>{{ $post->category->h1 }}</td>
<td>
#if ($post->published)
<span class="label label-success">Да</span>
#else
<span class="label label-danger">Нет</span>
#endif
</td>
<td>{{$post->updated_at}}</td>
<td>
<a href="#"type="button" class="btn btn-primary" data-toggle="tooltip" data-placement="left" title="Редактировать">
<i class="fa fa-edit"></i>
</a>
<a href="#" target="_blank" type="button" class="btn btn-success" data-toggle="tooltip" data-placement="top" title="Просмотреть">
<i class="fa fa-external-link"></i>
</a>
<form action="{{ action('PostController#destroy', ['id' => $post->id]) }}" method="post">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="_method" value="DELETE">
<button type="submit" class="btn btn-danger" data-toggle="tooltip" data-placement="right" title="В корзину">
<i class="fa fa-trash-o"></i>
</button>
</form>
</td>
</tr>
#endforeach
Error here <td>{{ $post->category->h1 }}</td>
Trying to get property of non-object (View: C:\OpenServer\domains\laravel\resources\views\admin\post\index.blade.php)
because you are naming your foreign key as category_id like the convention,i think you should define eloquent relationship like this
public function category() {
return $this->hasOne('App\Models\Category');
}
you should see hasOne method on Model.php file how to define one to one relationship.
Please check what fields your category table has!
Does it contains 'h1' field, you are accessing 'h1' key, but may be its not there at table

Resources