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

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 "

Related

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');
}

Change return View to return Route on laravel search function

I am trying to correct my code of the searchresult function of my controller so my concern is that when I paginate the search result or make form validation, I get the following error message : The GET method is not supported for this route. Supported methods: POST.
so if you can help me, I want to change my code from returning the view to returning the route.
here is my code
Route:
Route::get('/post/searchpost', 'PostsController#index')->name('index');
Route::post('/post/search_result', 'PostsController#searchresult')->name('searchresult');
Blades
//index
<div class="posts">
<h1>Posts</h1>
<div class="sreach">
<form action="{{route('searchresult', app()->getLocale())}}" method="POST">
{{ csrf_field()}}
<div class="form-row">
<div class="form-group col-md-2">
<label class="lbl" for="cat_id">title</label>
<select class="form-control" id="cat_id" name="cat_id">
<option value="" selected></option>
#foreach ($categoriesas $cat)
<option value="{{$cat->id}}">{{$cat->cat_mame}}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-2">
<label class="lbl" for="title">Post title</label>
<input type="text" class="form-control" id="title" name="title">
</div>
<div class="form-group col-md-2">
<label class="lbl" for="content">Post content</label>
<textarea class="form-control" id="content" name="content">
</textarea >
</div>
</div>
<center>
<button type="submit">search</button>
</center>
</form>
</div>
<table id="posts">
<thead>
<tr>
<th>{{__('main.title')}}</th>
<th>{{__('main.post_category')}}</th>
<th>{{__('main.content')}}</th>
</tr>
</thead>
<tbody>
#foreach($posts as $postkey => $post)
<tr>
<td>{{$post->title}}</td>
<td>{{$post->category->cat_name}}</td>
<td>{{$post->content}}</td>
</tr>
#endforeach
</tbody>
</table>
Blades
//searchresult
<div class="posts">
<h1>Posts</h1>
<div class="sreach">
//that make me search again in result page using the same form
<form action="{{route('searchresult', app()->getLocale())}}" method="POST">
{{ csrf_field()}}
<div class="form-row">
<div class="form-group col-md-2">
<label class="lbl" for="cat_id">title</label>
<select class="form-control" id="cat_id" name="cat_id">
<option value="" selected></option>
#foreach ($categoriesas $cat)
<option value="{{$cat->id}}">{{$cat->cat_mame}}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-2">
<label class="lbl" for="title">Post title</label>
<input type="text" class="form-control" id="title" name="title">
</div>
<div class="form-group col-md-2">
<label class="lbl" for="content">Post content</label>
<textarea class="form-control" id="content" name="content">
</textarea >
</div>
</div>
<center>
<button type="submit">search</button>
</center>
</form>
</div>
<table id="posts">
<thead>
<tr>
<th>{{__('main.title')}}</th>
<th>{{__('main.post_category')}}</th>
<th>{{__('main.content')}}</th>
</tr>
</thead>
<tbody>
#foreach($details as $detailkey => $detail)
<tr>
<td>{{$detail->title}}</td>
<td>{{$detail->category->cat_name}}</td>
<td>{{$detail->content}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
Controller
public function index()
{
$ctegories= Category::all();
return view('search')->with('posts', Post::all())->with('ctegories', $ctegories);
}
public function searchresult(Request $request)
{
$title= $request->title;
$content= $request->content;
$cat_id= $request->cat_id;
$posts= Post::where('title', 'like', '%' . $title. '%')
->whereHas('category', function(Builder $query) use ($sujet_id){
$query->where('id', $cat_id);
})
->orderBy('created_at','desc')
->get();
//for form dropdown categories
$categories= Category::all();
if(count ($posts) > 0)
{
//this what i want to change from view to route with those parameters
return view('searchresult')
->withDetails($posts)->withQuery($title)
->withCategories($categories);
} else {
return redirect()->route('index')->with('success','search not found');
}
}
So otherwise the function works perfectly and I get the data
i will appreciate your help thank you
You should use below method to return route with parameters:
return \Redirect::route('nameOfRoute', ['param1'=>'value1','param2'=>'value2',...])->with('message', 'Search found!!!');

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.

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');

How to insert values to table 'users' in laravel 5.2?

I want to insert employee details username,area to the table 'users'.
I have the following codes of CreateEmployeeController and
createemployee.blade.php view file.
When I click on the menu Create Employee is will shows the following error
QueryException in Connection.php line 662:
SQLSTATE[42000]: Syntax error or access violation: 1066 Table/alias: 'users' non unique (SQL: select * from users inner join users on users.id = users.users_id where users.deleted_at is null)
Controller file :
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Controllers\AdminController;
use App\CreateEmployee;
use App\Employee;
use App\Users;
class CreateEmployeeController extends AdminController
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
public function addemployee()
{
$employee = CreateEmployee::all();
$employee =CreateEmployee::join('users','users.id','=','users.users_id')->get();
return view('app.admin.employee.employee',compact('employee','users'));
}
public function employeesave(Request $request)
{
$title = 'Add Employee';
$employee = new Employee();
$employee->name=$request->employee_name;
$employee ->area = $request->area;
$employee->save();
Session::flash('flash_notification', array('level' => 'success', 'message' => 'employee created successfully'));
return Redirect::action('Admin\CreateEmployeeController#addemployee');
}
public function updateemployee(Request $request)
{
Employee::where('id',$request->id)->update(array('name'=>$request->employee_name,'area'=>$request->area));
Session::flash('flash_notification', array('level' => 'success', 'message' => 'shop details updated successfully'));
return Redirect::action('Admin\CreateEmployeeController#addemployee',array('id' => $request->id));
}
public function editemployee($id)
{
$employee = Employee::where('id',$id)->get();
return view('app.admin.employee.editemployee',compact('employee'));
}
public function deleteemployee($id)
{
$employee = Employee::where('id',$id)->get();
return view('app.admin.employee.delete',compact('employee'));
}
public function deleteconfirms($id)
{
$employee = Employee::where('id',$id)->delete();
Session::flash('flash_notification', array('level' => 'success', 'message' => 'customer deleted successfully'));
return Redirect::action('Admin\CreateEmployeeController#addemployee');
}
public function destroy($id)
{
//
}
}
//view file
#extends('app.admin.layouts.default')
{{-- Web site Title --}}
#section('title') {{{ trans('site/user.register') }}} :: #parent #stop
#section ('styles')
#parent
<style type="text/css">
</style>
#stop
{{-- Content --}}
#section('main')
#include('utils.vendor.flash.message')
<div class="row">
<div class="page-header">
<h2>Add Employee</h2>
</div>
</div>
<div class="container-fluid">
<div class="row">
#include('utils.errors.list')
<form class="form-horizontal" role="form" method="POST" action="{{ URL::to('admin/addemployee') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label">Employee Name</label>
<div class="col-md-2">
<input type="text" class="form-control" name="employee_name"
required>
</div>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label" for="religion">Password</label>
<div class="col-md-2">
<input type="password" class="form-control" placeholder="Password" name="password" id="password" data-parsley-trigger="change" data-parsley-required="true" data-parsley-minlength="6" data-parsley-maxlength="14" required>
{!! $errors->first('cpassword', '<label class="control-label" for="cpassword">:message</label>')!!}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label" for="caste">Confirm Password</label>
<div class="col-md-2">
<input type="password" class="form-control" placeholder="Confirm Password" name="password_confirmation" id="password_confirmation" data-parsley-trigger="change" data-parsley-required="true" data-parsley-equalto="#password" data-parsley-minlength="6" data-parsley-maxlength="14" required>
{!! $errors->first('password_confirmation', '<label class="control-label" for="password_confirmation">:message</label>')!!}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label">Area</label>
<div class="col-md-2">
<input type="text" class="form-control" name="area"
required placeholder="Area">
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-2 col-md-offset-2">
<button type="submit" class="btn btn-primary">
Add
</button>
</div>
</div>
</form>
</div>
</div>
<div class="invoice-content">
<div class="table-responsive">
<div class="col-md-offset-2">
<table class="table table-invoice">
<thead>
<tr>
<th>Employee Name</th>
<th>Area</th>
</tr>
</thead>
</div>
</div>
<tbody>
#foreach($addemployee as $employee)
<tr>
<td>{{$employee->employee_name}}</td>
<td>{{$employee->area}}</td>
<td>
Edit
<a onclick="return confirm('Are you Sure you want to do this Action!'); style.backgroundColor='#84DFC1'; " href="employee/delete/{{$employee->id}}">delete</a>
</td>
</tr>
#endforeach
#if(!count($employee))
<tr><td>NO data found </td></tr>
#endif
</tbody>
</tbody>
</table>
{{--</div>--}}
{{--</div>--}}
{{--</div>--}}
</div>
</div>
#endsection
I can't get the full idea about your problem, but as upto me I understand that - You are using same table/column names in your join statement, you can do this as:
$employee = CreateEmployee::join('users', 'create_employees.id','=', 'users.employee_id')->get();
Hope this helps!

Resources