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

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

Related

how to create SELECT * FROM `TABLE` WHERE user_id = id; in Laravel 8

I want to create a page that can show data where user_id = user_id logged in
here is my controller that select all data from table, i want to filter it with corresponding logged in user id
public function staffHome()
{
$posts = Post::latest()->paginate(5);
return view('staffHome', compact('posts'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
and here is my view
#foreach ($posts as $post)
<tr>
<td class="text-center">{{ ++$i }}</td>
<td>{{ $post->title }}</td>
<td class="text-center">
<form action="{{ route('posts.destroy',$post->id) }}" method="POST">
<a class="btn btn-info btn-sm" href="{{ route('posts.show',$post->id) }}">Show</a>
<a class="btn btn-primary btn-sm" href="{{ route('posts.edit',$post->id) }}">Edit</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Apakah Anda yakin ingin menghapus data ini?')">Delete</button>
</form>
</td>
</tr>
#endforeach
thanks in advance
your code should be like this
public function staffHome()
{
$posts = Post::where('user_id', Auth::id())->latest()->paginate(5);
return view('staffHome', compact('posts'))->with('i', (request()->input('page', 1) - 1) * 5);
}
You can do it like this
$posts = Post::where('user_id', Auth::id())->latest()->paginate(5);
Where Auth::id() is currently logged in user's id.
Or with relation
Auth::user()->posts()->->latest()->paginate(5);
$posts = Post::where('user_id', $user_id)->latest()->paginate(5);
Please see: https://laravel.com/docs/8.x/collections#method-where

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.

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

Trying to get property 'nom_matiere' of non-object laravel shows me this error

i want to display the name of matiere in this page but he shows me this error Trying to get property 'nom_matiere' of non-object
i make a selection in the note page to select the matiere then give a note to here it work but when i display the name of matiere in my table it give me error
model note
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Note extends Model
{
protected $fillable = ['note'];
public function matieres()
{
return $this->belongsToMany(Matiere::class);
}
}
model matiere
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Matiere extends Model
{
protected $fillable = ['nom_matiere','coef'];
public function notes() {
return $this->belongsToMany(Note::class);
}
}
my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Note;
use App\Matiere;
class NoteController extends Controller
{
public function index()
{
$notes = Note::paginate(5);
$matieres = Matiere::all();
return view('admin.notes',compact('notes','matieres'));
}
public function store(Request $request)
{
Note::create($request->all());
session()->flash('success',' cette note a été enregistré avec succés');
return redirect()->back();
}
public function update(Request $request, $id)
{
$note = Note::findOrFail($request->note_id);
$note = Matiere::findOrFail($request->note_id);
$note->update($request->all());
session()->flash('success','cette note a été modifié avec succés');
return redirect()->back();
}
public function destroy(Request $request)
{
$note = Note::findOrFail($request->note_id);
$note->delete();
session()->flash('success','cette note a été supprimé avec succés');
return redirect()->back();
}
}
my view
<section id="no-more-tables">
<table class="table table-bordered table-striped table-condensed cf">
<thead class="cf">
<tr>
<th>id-note</th>
<th>La note</th>
<th>nom matiere</th>
<th>les actions</th>
</tr>
</thead>
<tbody>
#foreach($notes as $note)
<tr>
<td class="numeric" data-title="id-note" >{{$note->id}}</td>
<td class="numeric" data-title="Nom">{{$note->note}}</td>
<td class="numeric" data-title="Nom">{{$note->matiere->nom_matiere}}</td>
<td>
<button href="#editEmployeeModal" class="btn btn-theme" data-target="#editEmployeeModal "data-mynote="{{$note->note}}" "data-mymatiere="{{$note->nom_matiere}}" data-catid={{$note->id}} class="edit" data-toggle="modal" ><i class="material-icons" data-toggle="tooltip" title="Edit"></i> </button>
<button href="#deleteEmployeeModal" class="btn btn-theme" data-target="#deleteEmployeeModal" data-catid={{$note->id}} class="delete" data-toggle="modal" > <i class="material-icons" data-toggle="tooltip" title="Delete"></i> </button>
</td>
</tr>
</tbody>
#endforeach
</table>
<div class="text-center">
{{ $notes->links() }}
</div>
<div class="clearfix">
<div class="hint-text">Affichage de <b>5</b> sur <b>25</b> entrées</div>
<div id="addEmployeeModal" href="create" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form action="{{route('notes.store')}}" method="post">
{{csrf_field()}}
<div class="modal-header">
<h4 class="modal-title">Ajouter note</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>La note</label>
<input type="text" id="note" name="note" class="form-control" required>
</div>
</div>
<div class="form-group select">
<select name="matiere_id">
<option value="">--selectionner la mtiére svp --</option>
#foreach($matieres as $matiere)
<option value="{{ $matiere->id }}">{{ $matiere->nom_matiere }}</option>
#endforeach
</select>
</select>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Annuler">
<input type="submit" class="btn btn-success" value="Ajouter">
</div>
</form>
</div>
</div>
You're calling $note->matiere in your view but the relationship is called matieres, which would be a collection.
Instead of:
<td class="numeric" data-title="Nom">{{ $note->matiere->nom_matiere }}</td>
You'd need:
<td class="numeric" data-title="Nom">
#foreach ($note->matieres as $matiere)
{{ $matiere->nom_matiere }}
#endforeach
</td>
I do however suspect that you have set your relationship up wrong. You've got the Note -> Matiere relationship set to belongsToMany, which means that you need a pivot table to contain the FK relationships. This would only be used if your Note is the child of many Matiere.
It does sound like you have your relationships set up wrong, but without really understanding what you're trying to do it's hard to tell you what exactly needs to be done.
Separate issue, but in your class update() method you've also got:
$note = Note::findOrFail($request->note_id);
$note = Matiere::findOrFail($request->note_id);
$note->update($request->all());
This means that you actually update the Matiere model no the Note model.

Resources