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

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.

Related

Why Does Image Read Null When I Try To Delete My Category?

I am trying to find a way to delete my category that I have created. I have the image stored in my public folder and I get the error attempt to read image is null, I think the error has to do with category_id being null. How can I retrieve it for my category object?
//Controller class
class Index extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public $category_id;
//setting category_id
public function deleteCategory($category_id)
{
$this->category_id = $category_id;
}
public function destroyCategory() {
$category = Category::find($this->category_id);
// dd($this);
$path = 'uploads/category/'.$category->image;
if (File::exists($path)) {
File::delete($path);
}
$category->delete();
session()->flash('message', 'Category Deleted');
$this->dispatchBrowserEvent('close-modal');
}
public function render()
{
$categories = Category::orderBy('id', 'DESC')->paginate(10);
return view('livewire.admin.category.index', ['categories' => $categories]);
}
}
this is my component blades file that accompanies it.
//my blade file
<div>
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Category Delete</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form wire:submit.prevent="destroyCategory">
<div class="modal-body">
<h6>Are you sure you want to delete this data?</h6>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Yes. Delete</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
#if(session('message'))
<div class="alert alert-success">{{session('message')}}</div>
#endif
<div class="card-header">
<h4>
Category
Add Category
</h4>
</div>
<div class="card-body">
{{-- display all categories using livewire --}}
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($categories as $category)
<tr>
<td>{{$category->id}}</td>
<td>{{$category->name}}</td>
<td>{{$category->status == '1' ? "Hidden" : "Visible"}}</td>
<td>
Edit
<a href="#" wire:click="deleteCategory({{$category->id}})" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
Delete
</a>
</tr>
#endforeach
</tbody>
</table>
<div>
{{$categories->links()}}
</div>
</div>
</div>
</div>
</div>
#push('script')
<script>
window.addEventListener('close-modal', event => {
$('#deleteModal').modal('hide');
})
</script>
#endpush
I wanted to add my sugestion as a comment, however is to long and it doesn't look good when i add the code, so i need to add a post.
I see that you are using deleteCategory() to get category_id and set it on a public varaible public $category_id;, when you get the variable then you try to delete the category with destroyCategory().
If that is true you don't need to create 2 functions for that,
so instead try and use this:
public function deleteCategory($category_id) {
$category = Category::find($category_id);
$path = 'uploads/category/'.$category->image;
// dd($path); <- try this on the debbuger, to see the path
if (File::exists($path)) {
File::delete($path);
}
$category->delete();
session()->flash('message', 'Category Deleted');
$this->dispatchBrowserEvent('close-modal');
}
Just use the function deleteCategory with the code of destroyCategory, and let the paramenter $category_id, because deleteCategory gets the id from the view
wire:click="deleteCategory({{$category->id}})"

Pre-Populating Parent Child Form from DB

I have tried prepopulating the forms from DB records, not happening for child form, I have use all conventions for Laravel table, pivot table etc., still nothing. The array display with the dd('$allTariffs') but doesn't show on view file, please help am stuck with
ErrorException
foreach() argument must be of type array|object, null given
Edit Component Code
<?php
namespace App\Http\Livewire\Admin;
use App\Models\Products;
use App\Models\Tariffs;
use Livewire\Component;
class AdminEditTariffsComponent extends Component
{
// public $productId;
public $tariffId;
public $allTariffs = [];
public $rowProducts = [];
public $tariffName;
public function mount ($tariffId)
{
$this->rowProducts = Products::all();
$tariff = Tariffs::where('id', $tariffId)->first();
$this->tariffName = $tariff->tariff_name;
// $allTariffs = $tariff->products()->where('tariffs_id', $tariffId)->get()->toArray();
$allTariffs = $tariff->products->find($tariffId);
// var_dump($allTariffs) ;
// dd( $allTariffs);
foreach ($allTariffs->products as $product)
{
['productId' => $product->pivot->products_id, 'basicCharge' => $product->pivot->basic_charge, 'additionalCharge' => $product->pivot->additional_charge];
}
}
public function updateStatus()
{
$tariff = Tariffs::find($this->tariffId);
$tariff->tariff_name = $this->tariffName;
$tariff->created_by = auth()->user()->id;
$tariff->save();
foreach ($this->allTariffs as $product) {
$tariff->products()->sync($product['productId'],
['basic_charge' => $product['basicCharge'],
'additional_charge' => $product['additionalCharge']]);
}
session()->flash('message', 'Tariff added successfully!');
return redirect('/admin/tariffs/');
}
public function addProduct()
{
$this->allTariffs[] = ['productId' => '', 'basicCharge' => '', 'additionalCharge' => ''];
}
public function removeProduct($index)
{
unset($this->allTariffs[$index]);
$this->allTariffs = array_values($this->allTariffs);
}
public function render()
{
$rowProducts = Products::all();
return view('livewire.admin.admin-edit-tariffs-component',['rowProducts'=>$rowProducts])->layout('layouts.admin.base');
}
}
Edit View
<div class="container-fluid">
<!-- Begin Page Content -->
<!-- Page Heading -->
<div class="row">
<div class="col-lg-8">
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Edit Tariff</h6>
</div>
<div class="card-body">
<form wire:submit.prevent="editTariff">
#csrf
<div class="form-row">
<!-- Default input -->
<div class="form-group col-md-8">
<input type="text" class="form-control" placeholder="Enter Tariff Name"
wire:model="tariffName" required>
</div>
</div>
<hr>
<div class="card">
<div class="card-header">
<h6 class="text-primary">Products, Basic and Weight Charges</h6>
</div>
<div class="card-body">
<table class="table" id="products_table">
<thead>
<tr>
<th>Product</th>
<th>Basic Charge</th>
<th>Weight Charge</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach ($allTariffs as $index => $allTariff)
<tr wire:key="tariff-{{ $value->wireKey }}">
<td>
<select
wire:model="allTariffs.{{$index}}.productId"
class="custom-select custom-select-sm form-control form-control-sm">
<option value="">Select Product</option>
#foreach ($rowProducts as $product)
<option value="{{ $product->id }}">
{{ $product->product_name }}
</option>
#endforeach
</select>
</td>
<td>
<input type="text"
class="form-control custom-select-sm form-control form-control-sm"
placeholder="Basic Charge"
wire:model="allTariffs.{{$index}}.basicCharge" required>
</td>
<td>
<input type="text"
class="form-control custom-select-sm form-control form-control-sm"
placeholder="Weight Charge"
wire:model="allTariffs.{{$index}}.additionalCharge" required>
</td>
<td>
<a href="#" wire:click.prevent="removeProduct({{$index}})" class="btn btn-danger btn-circle btn-sm">
<i class="fas fa-trash"></i>
</a>
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="row">
<div class="col-md-12">
<a href="#" wire:click.prevent="addProduct" class="btn btn-success btn-circle btn-sm">
<i class="fas fa-plus"></i>
</a>
</div>
</div>
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-3">
<button type="submit" class="form-control btn btn-small btn-primary">Edit
Tariff</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
Model File
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tariffs extends Model
{
use HasFactory;
protected $table = "tariffs";
public function products()
{
return $this->belongsToMany(Products::class, 'products_tariffs',
'products_id', 'tariffs_id')
->withPivot('basic_charge', 'additional_charge');
}
public function productstariffs()
{
return $this->hasMany(ProductsTariffs::class);
}
}
I have tried prepopulating the forms from DB records, not happening for child form, I have use all conventions for Laravel table, pivot table etc., still nothing. The array display with the dd('$allTariffs') but doesn't show on view file, please help am stuck with
ErrorException
foreach() argument must be of type array|object, null given .thankyou
In your foreach in your mount function, you are creating an array but you aren't assigning it to anywhere. Therefore, $allTariffs is empty.
Also, you're casting your variables by default as an array. You are setting $rowProducts as a Collection, however. But then in your render you are also getting the $rowProducts again. I'd suggest removing the = [] and removing the fetching of the $rowProducts each render.
public $allTariffs = [];
public $rowProducts;
public $tariffName;
public function mount ($tariffId)
{
$this->rowProducts = Products::all();
// This assumes the $tarrifId always exists. If this isn't the case, perhaps
// wrap the related code in an "if ($tariff instanceof Tariff)"
$tariff = Tariffs::find($tariffId);
$this->tariffName = $tariff->tariff_name;
foreach ($tariff->products as $product) {
$this->allTariffs[] = ['productId' => $product->id, 'basicCharge' => $product->pivot->basic_charge, 'additionalCharge' => $product->pivot->additional_charge];
}
}
public function render()
{
return view('livewire.admin.admin-edit-tariffs-component')->layout('layouts.admin.base');
}

How I can display data using wheredoesnthave

I have one problem.i have group table
This table has many to many relationship with users table and I have declared the relationship in both model.
And this is join table
Group.php
class Group extends Model
{
use SoftDeletes;
use HasFactory;
public $timestamps=true;
protected $dates = ['deleted_at'];
public function creators()
{
return $this->belongsToMany(User::class);
}
}
User.php
class User extends Authenticatable
{
use SoftDeletes;
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $dates = ['deleted_at'];
public function grp()
{
return $this->belongsToMany(Group::class);
}
}
This is the page where it will display the group that user have request
And supposedly in this page it will display the group that user have not request yet which is line no 3.
This is the code of my project.
Controller
public function redirectFunct(Request $request)
{
$role=Auth::user()->role;
$userid=Auth::user()->id;
if($role=='3')
{
$user = User::find(Auth::user()->id);
$groups=Group::with('creators');
$exists = Group::whereDoesntHave('creators', function ($query) {
$query->where('user_id', '=', Auth::user()->id);
})->get();
if($exists)
{
$users=Join::where('userID', '=', Auth::user()->id)->get();
}
$request = Join::where('userApprove','=','0')->where('userID',$userid)->get();
return view('member.dashboard',['users'=>$users,'user'=>$user,'groups'=>$groups,'exists'=>$exists,'request'=>$request]);
}
dasboard.blade.php
//sugessted group tab
<div class="tab-pane fade" id="sales" role="tabpanel" aria-labelledby="sales-tab">
<div class="row">
<div class="col-md-12 stretch-card">
<div class="card">
<div class="card-body">
<li class="nav-item nav-search d-none d-lg-block w-100">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="search">
<i class="mdi mdi-magnify"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="Search now" aria-label="search" aria-describedby="search">
</div>
</li>
<br>
<div class="table-responsive">
<table id="" class="table">
<thead>
<tr>
<th>No.</th>
<th>Group Name</th>
<th>Group Description</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($exists as $group)
<tr>
<td>{{$loop->iteration}}</td>
<td>{{$group->groupName}}</td>
<td>{{$group->groupDesc}}</td>
<td>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModalCenter{{$group->id}}">Details</button>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter{{$group->id}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Group Details</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Group Name:{{$group->groupName}}</p>
<p>Group Description : {{$group->groupDesc}}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</td>
<td><a href="{{url('/join',$group->id)}}"><button type="button" class="btn btn-secondary .btn-{color}">Join</button></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
//pending group tab
<div class="tab-pane fade" id="t" role="tabpanel" aria-labelledby="t-tab">
<div class="row">
<div class="col-md-12 stretch-card">
<div class="card">
<div class="card-body">
<div class="table-responsive">
<table id="" class="table">
<thead>
<tr>
<th>No.</th>
<th>Group Name</th>
<th>Group Description</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($request as $req)
<tr>
<td>{{$loop->iteration}}</td>
<td>{{$req->group->groupName}}</td>
<td>{{$req->group->groupDesc}}</td>
<td><a href ="{{url('/cancelrequest',$req->id)}}"><button type="button" class="btn btn-danger .btn-{color}" onclick="return confirm('Are you sure?')">Cancel</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I really appreciated if someone help me, please inform if there is not enough information, I will add it ASAP.

adding data in table show me error when i add the relation ships

I am a beginner in laravel I made a relationship one to many between the table of father and the table of eleve after that when i try to add a a new student he shows this error
SQLSTATE[HY000]: General error: 1364 Field 'father_id' doesn't have a default value (SQL: insert into eleves (nom, prenom, adresse, date_naiss, sexe, nationnalite, niveau_scolaire, updated_at, created_at) values (mohamed, ferchichi, tunis, 2018-07-22, Un garçon, tunisen, 1, 2019-05-13 10:56:28, 2019-05-13 10:56:28))
how I can correct this problem i need your help
this is the table of eleve
public function up()
{
Schema::create('eleves', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('father_id');
$table->string('nom');
$table->string('prenom');
$table->date('date_naiss');
$table->string('sexe');
$table->string('nationnalite');
$table->string('niveau_scolaire');
$table->string('adresse');
$table->foreign('father_id')->references('id')->on('fathers')->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
}
the model of eleve
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Eleve extends Model
{
protected $fillable = ['nom', 'father_id', 'prenom', 'date_naiss', 'sexe', 'nationnalite', 'niveau_scolaire', 'adresse'];
public function father()
{
return $this->belongsTo('App\Father');
}
}
the model of father
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Father extends Model
{
protected $fillable = ['nom', 'prenom', 'adresse', 'num_tel', 'email', 'login', 'date_naissance ', 'password'];
public function user()
{
return $this->belongsTo(User::class);
}
public function eleve()
{
return $this->hasMany('App\Eleve');
}
and the blade of eleve
<section id="no-more-tables">
<table class="table table-bordered table-striped table-condensed cf">
<thead class="cf">
<tr>
<th>id-eleve</th>
<th>Nom</th>
<th>Prenom</th>
<th>Adresse</th>
<th>Age</th>
<th>Sexe</th>
<th>Nationnalité</th>
<th>Niveau scolaire </th>
<th>les actions</th>
</tr>
</thead>
<tbody>
#foreach($eleves as $eleve)
<tr>
<td class="numeric" data-title="id-parent">{{$eleve->id}}</td>
<td class="numeric" data-title="Nom">{{$eleve->nom}}</td>
<td class="numeric" data-title="Prenom">{{$eleve->prenom}}</td>
<td class="numeric" data-title="Adresse">{{$eleve->adresse}}</td>
<td class="numeric" data-title="Numéro telephone">{{$eleve->date_naiss}}</td>
<td class="numeric" data-title="Email">{{$eleve->sexe}}</td>
<td class="numeric" data-title="Login">{{$eleve->nationnalite}}</td>
<td class="numeric" data-title="Password">{{$eleve->niveau_scolaire}}</td>
<td>
<button href="#editEmployeeModal" class="btn btn-theme" data-target="#editEmployeeModal "
data-mytitle="{{$eleve->nom}}" data-myprenom="{{$eleve->prenom}}"
data-myadresse="{{$eleve->adresse}}" data-myage="{{$eleve->date_naiss}}"
data-mysexe="{{$eleve->sexe}}" data-mynationalite="{{$eleve->nationnalite}}"
data-myniveau="{{$eleve->niveau_scolaire}}" data-catid={{$eleve->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={{$eleve->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">
{{ $eleves->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('eleves.store')}}" method="post">
{{csrf_field()}}
<div class="modal-header">
<h4 class="modal-title">Ajouter un éléve</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>nom</label>
<input type="text" id="nom" name="nom" class="form-control" required>
</div>
<div class="form-group">
<label>prenom</label>
<input type="text" id="prenom" name="prenom" class="form-control" required>
</div>
<div class="form-group">
<label>adresse</label>
<textarea name="adresse" id="adresse" class="form-control" required></textarea>
</div>
<div class="form-group">
<label for="start">Date Naissance</label>
<input type="date" id="date_naiss" name="date_naiss" value="2018-07-22" min="2018-01-01"
max="2030-12-31">
<!-- <label>Date Naissance</label>
<input type="text" name=" date_naiss" id="date_naiss" class="form-control" required>
</div> -->
</div>
<div class="form-group">
<div>
<input type="radio" id="sexe" name="sexe" value="une fille" checked>
<label for="sexe">une fille</label>
</div>
<div>
<input type="radio" id="sexe" name="sexe" value="Un garçon">
<label for="sexe">Un garçon</label>
</div>
</div>
<div class="form-group">
<label>Nationnalité</label>
<input type="text" name="nationnalite" id="nationnalite" class="form-control" required>
</div>
<div class="form-group">
<label>Niveau Scolaire</label>
<input type="text" name="niveau_scolaire" id="niveau_scolaire" class="form-control"
required>
</div>
</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>
</div>
</div>
</section>
the controller of student
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Eleve;
class EleveController extends Controller
{
public function index()
{
$eleves = Eleve::paginate(5);
return view('admin.eleves',compact('eleves'));
}
public function store(Request $request)
{
Eleve::create($request->all());
session()->flash('success',' Cet nouvel éléve a été enregistré avec succés');
return redirect()->back();
}
public function update(Request $request, $id)
{
$eleve = Eleve::findOrFail($request->eleve_id);
$eleve->update($request->all());
session()->flash('success','Cet éléve a été modifié avec succés');
return redirect()->back();
}
public function destroy(Request $request)
{
$eleve = Eleve::findOrFail($request->eleve_id);
$eleve->delete();
session()->flash('success','Cet éleve a été supprimé avec succés');
return redirect()->back();
}
}
The father_id field in the eleves table is required. You either have to make it optional or, more likely, add it to your form.
To make the field optional replace this line
$table->unsignedBigInteger('father_id');
with
$table->unsignedBigInteger('father_id')->nullable();
To add it to the form you would probably use a <select>, something like:
<form ...>
<select name="father_id">
#foreach(\App\Father::all() as $father)
<option name="{{ $father->id }}">{{ $father->nom }}</option>
#endforeach
</select>
Note: It's bad practice to call the database inside a view file. A better approach would be to load the Fathers inside the controller and pass it to the view:
public function create()
{
$fathers = Father::all();
return view('...', ['fathers' => $fathers]);
}
and in the view:
<form ...>
<select name="father_id">
#foreach($fathers as $father)
<option name="{{ $father->id }}">{{ $father->nom }}</option>
#endforeach
</select>
in the EleveController i add use App\Father; and i add this function
public function create()
{
$fathers= Father::all();
return view('admin.eleves',compact('fathers'));
}
and in the eleve blade.php i add this
<select name="father_id">
#foreach($fathers as $father)
<option name="{{ $father->id }}">{{ $father->nom }}</option>
#endforeach
</select>
the problem is that shows me the same error "Undefined variable: fathers "

I have a problem when I display data in my view

I am a beginner in laravel and I have a graduation project I develop a school management application I have a one to many relationship between parent and student and I have to display the parent name but it does not work
this error Undefined variable: father (View: C:\xampp\htdocs\ecole\resources\views\admin\eleves.blade.php)
<tr>
<th>id-eleve</th>
<th>Nom</th>
<th>Prenom</th>
<th>Adresse</th>
<th>Age</th>
<th>Sexe</th>
<th>Nationnalité</th>
<th>Niveau scolaire </th>
<th>les actions</th>
</tr>
</thead>
<tbody>
#foreach($father->eleves as $eleve)
<tr>
<td class="numeric" data-title="id-parent" >{{$eleve>id}}</td>
<td class="numeric" data-title="Nom">{{$eleve->nom}}</td>
<td class="numeric" data-title="Prenom">{{$eleve->prenom}}</td>
<td class="numeric" data-title="Adresse">{{$eleve->adresse}}</td>
<td class="numeric" data-title="Numéro telephone">{{$eleve->date_naiss}}</td>
<td class="numeric" data-title="Email">{{$eleve->sexe}}</td>
<td class="numeric" data-title="Login">{{$eleve->nationnalite}}</td>
<td class="numeric"data-title="Password">{{$eleve->niveau_scolaire}}</td>
<td class="numeric"data-title="Password">{{$father->nom}}</td>
<td>
In controller:
public function index(){
$fathers = Father::all();
return view('admin.eleves', compact('fathers');
}
In blade file:
#forelse($fathers as $father)
<td class="numeric" data-title="id-parent" >{{$father->id}}</td>
#empty
#endforelse
Post your controller code. The error is that blade does not recognize a father variable so something on your backend has gone wrong. Should look something like this.
class YourController extends Controller
{
public function example()
{
$father = YourFatherModel::all();
return view('app.main', compact('father'));
}
}
You might have the variable spelling wrong or you haven't sent the variable to the blade file. Try one of these
$father=Father::all();
return view('admin.eleves', compact('father'));
OR:
$data['father']=Father::all();
return view('admin.eleves', $data);
when I added the parent name in a select I want that when I add a student I have to choose his parent the problem is when I display it he shows me every time the first parent id
this is my view
<tr>
<th>id-eleve</th>
<th>Nom</th>
<th>Prenom</th>
<th>Adresse</th>
<th>Age</th>
<th>Sexe</th>
<th>Nationnalité</th>
<th>Niveau scolaire </th>
<th>Niveau scolaire </th>
<th>les actions</th>
</tr>
</thead>
<tbody>
#foreach($eleves as $eleve)
<tr>
<td class="numeric" data-title="id-parent" >{{$eleve->id}}</td>
<td class="numeric" data-title="Nom">{{$eleve->nom}}</td>
<td class="numeric" data-title="Prenom">{{$eleve->prenom}}</td>
<td class="numeric" data-title="Adresse">{{$eleve->adresse}}</td>
<td class="numeric" data-title="Numéro telephone">{{$eleve->date_naiss}}</td>
<td class="numeric" data-title="Email">{{$eleve->sexe}}</td>
<td class="numeric" data-title="Login">{{$eleve->nationnalite}}</td>
<td class="numeric"data-title="Password">{{$eleve->niveau_scolaire}}</td>
#foreach($fathers as $father)
<td class="numeric"data-title="Password">{{$father->nom}}{{$father->prenom}}</td>
#endforeach
<td>
<button href="#editEmployeeModal" class="btn btn-theme" data-target="#editEmployeeModal "data-mytitle="{{$eleve->nom}}" data-myprenom="{{$eleve->prenom}}" data-myadresse="{{$eleve->adresse}}" data-myage="{{$eleve->date_naiss}}" data-mysexe="{{$eleve->sexe}}" data-mynationalite="{{$eleve->nationnalite}}" data-myniveau="{{$eleve->niveau_scolaire}}" data-catid={{$eleve->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={{$eleve->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">
{{ $eleves->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('eleves.store')}}" method="post">
{{csrf_field()}}
<div class="modal-header">
<h4 class="modal-title">Ajouter un éléve</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>nom</label>
<input type="text" id="nom" name="nom" class="form-control" required>
</div>
<div class="form-group">
<label>prenom</label>
<input type="text" id="prenom" name="prenom" class="form-control" required>
</div>
<div class="form-group">
<label>adresse</label>
<textarea name="adresse" id="adresse" class="form-control" required></textarea>
</div>
<div class="form-group">
<label for="start">Date Naissance</label>
<input type="date" id="date_naiss" name="date_naiss"
value="2018-07-22"
min="2018-01-01" max="2030-12-31">
</div>
<div class="form-group">
<div>
<input type="radio" id="sexe" name="sexe" value="une fille"
checked>
<label for="sexe">une fille</label>
</div>
<div>
<input type="radio" id="sexe" name="sexe" value="Un garçon">
<label for="sexe">Un garçon</label>
</div>
</div>
<div class="form-group">
<label>Nationnalité</label>
<input type="text" name="nationnalite" id="nationnalite" class="form control" required>
</div>
<div class="form-group">
<label>Niveau Scolaire</label>
<input type="text" name="niveau_scolaire" id="niveau_scolaire" class="form-control" required>
</div>
</div>
<select name="father_id">
#foreach($fathers as $father)
<option value="{{ $father->id }}">{{ $father->nom }}</option>
#endforeach
</select>
<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>
this is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Eleve;
use App\Father;
class EleveController extends Controller
{
public function index()
{
$eleves = Eleve::paginate(5);
$fathers = Father::all();
return view('admin.eleves',compact('eleves', 'fathers'));
}
public function create()
{
$fathers = Father::all();
return view('admin.eleves', ['fathers' => $fathers]);
}
public function store(Request $request)
{
Eleve::create($request->all());
session()->flash('success',' Cet nouvel éléve a été enregistré avec succés');
return redirect()->back();
}
public function update(Request $request, $id)
{
$eleve = Eleve::findOrFail($request->eleve_id);
$eleve->update($request->all());
session()->flash('success','Cet éléve a été modifié avec succés');
return redirect()->back();
}
public function destroy(Request $request)
{
$eleve = Eleve::findOrFail($request->eleve_id);
$eleve->delete();
session()->flash('success','Cet éleve a été supprimé avec succés');
return redirect()->back();
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Eleve;
use App\Father;
class EleveController extends Controller
{
public function index()
{
$eleves = Eleve::paginate(5);
$fathers = Father::all();
return view('admin.eleves',compact('eleves', 'fathers'));
}
public function create()
{
$fathers = Father::all();
return view('admin.eleves', ['fathers' => $fathers]);
}
public function store(Request $request)
{
Eleve::create($request->all());
session()->flash('success',' Cet nouvel éléve a été enregistré avec succés');
return redirect()->back();
}
public function show($id)
{
}
public function update(Request $request, $id)
{
$eleve = Eleve::findOrFail($request->eleve_id);
$eleve->update($request->all());
session()->flash('success','Cet éléve a été modifié avec succés');
return redirect()->back();
}
public function destroy(Request $request)
{
$eleve = Eleve::findOrFail($request->eleve_id);
$eleve->delete();
session()->flash('success','Cet éleve a été supprimé avec succés');
return redirect()->back();
}
}
the route
Route::resource('eleves','EleveController');

Resources