Laravel 7 Relationship many to many not working - laravel

An event can be in one to several years and a year can have several events, hence the use of the many-to-many relationship.
So I have 3 tables: evenements, years and evenement_year (pivot table).
I carefully read the Laravel 7 documentation and thought I had followed the procedure :
Evenement Model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Evenement extends Model
{
protected $fillable = ['name', 'year_id','mnemonique','color'];
//One yar can have severals events and I give the name events_years to pivot
public function years()
{
return $this->belongsToMany(Year::class, 'evenement_year');
}
}
Year Model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Year extends Model
{
protected $fillable = ['name'];
public function evenements()
{
// a event can be in several years and I give the name events_years to pivot
return $this->belongsToMany(Evenemnt::class, 'evenement_year');
}
}
When I try to SELECT all events with years with this code (in the EventementController) at the index method :
<?php
namespace App\Http\Controllers;
use App\Evenement;
use App\EvenementType;
use App\Type;
use App\Year;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use stdClass;
class EvenementController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$evenements = Evenement::orderBy('year_id')->orderBy('mnemonique')->get();
$years = Year::all();
$evenTypes= EvenementType::all();
$types= Type::All();
return view('evenement.index', compact('evenements', 'years','evenTypes','types'));
}
}
I have this error :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'year_id' in
'order clause' (SQL: select * from evenements order by year_id
asc, mnemonique asc)
Thank you for your help and have a nice Sunday.
Edit :
This is the view code :
#extends('adminlte::page')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/spectrum-colorpicker2/dist/spectrum.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/spectrum-colorpicker2/dist/spectrum.min.css">
#section('title', 'Cours')
#section('content_header')
<h1>Liste des évènements</h1>
#stop
#section('content')
<p>La liste de tous les évènements enregistrer</p>
<div class="card">
<div class="card-header">
Ajouter un événement
</div>
<div class="filtre">
<p margin:50>Selectionner une année <br>
<SELECT name="filtreAnnée" margin: 50>
<libellé>Selectionner une année</libellé>
<option valeur="tout">Toutes les années</option>
<option valeur="BA1">BA1</option>
<option valeur="BA2">BA2</option>
<option valeur="BA3">BA3</option>
<option valeur="MA1">MA1</option>
<option valeur="MA2">MA2</option>
</SELECT>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Mnémonique</th>
<th>Nom</th>
<th>Année</th>
<th>Couleur</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($evenements as $evenement)
<tr style="outline: thin solid">
<td>{{ $evenement->mnemonique }}</td>
<td>{{ $evenement->name }}</td>
<td>{{ $evenement->year->name }}</td>
<td>{{ $evenement->color}}</td>
<td>
<button type="button" class="btn btn-sm btn-warning" id="edit" data-toggle="modal" data-target="#edit-modal-{{ $evenement->id }}">
<i class="far fa-edit"></i>
</button>
#include('evenement.update')
<button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#delete-modal-{{ $evenement->id }}">
<i class="far fa-trash-alt"></i>
</button>
#include('evenement.delete')
</td>
</tr>
<?php $displayTh = false ?>
#foreach ($evenTypes as $evenT)
#if (!$displayTh)
<?php $displayTh=true ?>
<tr>
<th> </th>
<th>Type de cours </th>
<th>Nombre d'heure</th>
<th>
<button type="button" class= "btn btn-sm btn-primary" data-toggle="modal" data-target="#create-type-modal-{{ $evenement->id }}">
<i class="fa fa-plus-circle" aria-hidden="true"></i>
</button>
#include('evenement.createEvenementType')
</th>
</tr>
#endif
#if ($evenement->id == $evenT->evenement_id )
<tr>
<td> </td>
<td>{{$evenT->type->name}}</td>
<td>{{$evenT->total_hours}}</td>
<td><button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#delete-type-modal-{{ $evenT->id }}">
<i class="fas fa-minus-circle"></i>
</button>
#include('evenement.deleteEvenementType')
</td>
</tr>
#endif
#endforeach
<tr></tr>
#endforeach
<script>
$(".basic").spectrum();
</script><!-- palette de couleur-->
</tbody>
</table>
</div>
</div>
</div>
#stop
#section('css')
#stop
#section('js')
#stop
edit 2 (dd to array)
I need name from array62 and name from array 5 for example.
array:62 [▼
0 => array:7 [▼
"id" => 61
"name" => "Accueil"
"mnemonique" => "Accueil"
"color" => "#bcbcbc"
"created_at" => "2021-07-13T14:16:04.000000Z"
"updated_at" => null
"years" => array:2 [▼
0 => array:5 [▼
"id" => 1
"name" => "BA1"
"created_at" => "2021-07-13T14:16:04.000000Z"
"updated_at" => null
"pivot" => array:2 [▶]
]
1 => array:5 [▼
"id" => 4
"name" => "MA1"
"created_at" => "2021-07-13T14:16:04.000000Z"
"updated_at" => null
"pivot" => array:2 [▶]
]
] ]

using with we can order by related data
For Ascending order
$evenements = Evenement::with(['years'=>function ($query){
$query->orderBy('year_id');
}])->get();
For Descending order
$evenements = Evenement::with(['years'=>function ($query){
$query->orderByDesc('year_id');
}])->get();
For retrieving those Evenement which has years then
$evenements = Evenement::with(['years'=>function ($query){
$query->orderByDesc('year_id');
}])->has('years')->get();
To get related table columns if its in blade file then
#foeach($evenements as $event)
#if(isset($event->years)&&count((array)$event->years))
#foreach($event->years as $year)
{{$year->name??null}}
#endforeach
#endif
#endforeach

Related

laravel store combined data as object in a single field

I am trying to store repeater data in database Using laravel. But for that I need to combine some data with different values.
my form looks like this--
<div v-for="(tab, tabIndex) in tabs" :key="tab.id">
<div class="col-md-4 offset-md-4 d-flex">
<label>HouseAreaTypes</label>
</div>
<div class="col-md-4 offset-md-4 d-flex">
<select
v-model="tab.selectedHouseType"
#change="getDecor(tabIndex)"
name="houseAreaTypeId">
<option v-for="houseType in houseTypes" :key="houseType.id" :value="houseType.id">{{ houseType.name }}</option>
</select>
<div class="col-md-4">
<button #click="addTab">
<i class="fa fa-plus"></i>
</button>
<button v-if="tabIndex > 0" class="btn btn-danger btn-sm mt-2 ml-2" #click="removeTab(tabIndex, tab)">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div v-for="(row, rowIndex) in tab.rows" :key="row.id">
<table class="table table-borderless col-md-12">
<thead>
<th>DecorationType</th>
<th>Description</th>
<th class="col-md-2">Rate</th>
<th>Quantity</th>
<th class="col-md-2">TotalAmount</th>
<th class="col-md-2"></th>
</thead>
<tbody>
<td>
<select
v-model="row.selectedDecor"
#change="getDescription(tabIndex,rowIndex) "name="decId">
<option v-for="decorType in tab.decorTypes" :key="decorType.id" :value="decorType.id">
{{ decorType.name }}
</option>
</select>
</td>
<td class="col-md-3">
<input type="text" name="des" v-model="row.selectedDes"/>
</td>
<td class="col-md-2">
<input type="number" name="rate" v-model="row.selectedRate" #change="calculateLineTotal(tabIndex,rowIndex)"
/>
</td>
<td class="col-md-1">
<input type="number" min="0" name="qty" v-model="row.selectedQty" #change="calculateLineTotal(tabIndex,rowIndex)"
/>
</td>
<td class="col-md-3">
<input
type="number" name="totalAmount" v-model="row.line_total"/>
</td>
<td>
<button v-if="rowIndex == Object.keys(tab.rows).length -1" type="button" class="btn btn-success btn-sm mt-2 ml-2" #click="addRow(tabIndex)">
<i class="fa fa-plus"></i>
</button>
<button type="button"
#click="removeRow(rowIndex, row,tabIndex)">
<i class="fa fa-minus"></i>
</button>
</td>
</tbody>
</table>
<hr />
</div>
</div>
my migration looks like this--
Schema::create('house_area_carts', function (Blueprint $table) {
$table->id();
$table->integer('houseAreaTypeId')->nullable();
$table->text('houseAreaCartInfo')->nullable()->comment('Object (decorationTypeId, descriptionOfDecoration, qty, rate, totalAmount)');
$table->timestamps();
});
I already have done the frontend part using vue. Here I need to store multiple houseAreaTypeId but in the houseAreaCartInfo I need to commbine decorationTypeId, descriptionOfDecoration, qty, rate, totalAmount these datas. I am attaching an image so you understand well
Iamge to understand the topic
updates
in my controller --
public function createCart(Request $request, $id)
{
$cart = HouseAreaCart::create([
'houseAreaTypeId' => $request->houseAreaTypeId,
'houseAreaCartInfo' => $request->get('houseAreaCartInfo'),
'houseAreaCartInfo' =>[
'rate' => $request->rate,
'qty' => $request->qty,
'decId' => $request->decId,
'des' => $request->des,
'totalAmount' => $request->totalAmount
]
]);
dd($cart);
return response()->json($cart);
}
I am getting this after dd.
"houseAreaTypeId" => "2"
"houseAreaCartInfo" => "{"rate":["11","2"],"qty":["8","1"],"decId":["2","3"],"des":["Nostrum dolorem qui","Veniam architecto l"],"totalAmount":["88.00","2.00"]}"
But when I add another houseAreaTypeId it's showing only the last houseAreaTypeId I added.
Now how do I process multiple houseAreaTypeId in my controller and save it in the database?
The easieast way will be attribute casting to json or array:
// add to the model:
protected $casts = [
'houseAreaCartInfo' => 'array',
];
https://laravel.com/docs/9.x/eloquent-mutators#array-and-json-casting
In the controller you would simply assign to the model an array from your request (or use update method on the model - will work the same):
$cartModel->houseAreaCartInfo = $request->get('houseAreaCartInfo');
then whenever you get that value it will come as an array (same as in the request):
$cartModel->houseAreaCartInfo
[
'des' => ...,
'qty' => ...,
...
]
In your request I suggest validation to make sure this value comes as an array and is stored properly
https://laravel.com/docs/9.x/validation#validating-arrays
Your migration should like,
$table->text('houseAreaCartInfo')->nullable()
anf then, Make sure your request is something like the following,
$request = [
'houseAreaTypeId' => 'required|int', //or array as your choice
'houseAreaCartInfo' => 'required|array',
'houseAreaCartInfo.*.decerationType' => 'required|array', //or int as your choice
'houseAreaCartInfo.*.description' => 'required|string',
'houseAreaCartInfo.*.rate' => 'required|int',
'houseAreaCartInfo.*.quantity' => 'required|int',
];
Then in your model, cast the column as array,
protected $cast = [
'houseAreaCartInfo' => 'array'
];
Finally, you can create model by using eloquent, There should be no error.

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.

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.

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