Change return View to return Route on laravel search function - laravel

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

Related

Laravel - How to apply Laravel old() helper function on dynamic input form

In Laravel-5.8 project, I am working on dynamic input form.
The main model is AppraisalGoal while the second model is AppraisalGoalDetail
Controller
public function create()
{
$goal = new AppraisalGoal();
$goaldetail = new AppraisalGoalDetail();
return view('appraisal.appraisal_goals.create')
->with('goal', $goal)
->with('goaldetail', $goaldetail) ;
}
public function store(StoreAppraisalGoalRequest $request)
{
DB::beginTransaction();
try {
$goal = new AppraisalGoal();
$goal->weighted_score = $request->weighted_score;
$goal->goal_title = $request->goal_title;
$goal->goal_description = $request->goal_description;
if ($request->appraisal_doc != "") {
$appraisal_doc = $request->file('appraisal_doc');
$new_name = rand() . '.' . $appraisal_doc->getClientOriginalExtension();
$appraisal_doc->move(public_path('storage/documents/appraisal_goal'), $new_name);
$goal->appraisal_doc = $new_name;
}
$goal->save();
foreach ( $request->activity as $key => $activity){
$startDate = Carbon::parse($request->start_date[$key]);
$endDate = Carbon::parse($request->end_date[$key]);
$insert_array = [
'kpi_description' => $request->kpi_description[$key],
'activity' => $request->activity[$key],
'start_date' => $startDate ->toDateTimeString(),
'end_date' => $endDate->toDateTimeString(),
];
AppraisalGoalDetail::create($insert_array );
}
DB::commit();
Session::flash('success', 'Goal is created successfully');
return redirect()->route(goals.index');
} catch (Exception $exception) {
DB::rollback();
Session::flash('error', 'Action failed! Please try again');
return redirect()->route('goals.index');
}
}
the create.blade view is shown below
<form action="{{route('goals.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Title:<span style="color:red;">*</span></label>
<input type="text" name="goal_title" value="{{ old('goal_title', $goal->goal_title) }}" placeholder="Enter goal title here" class="form-control">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Goal Description</label>
<textarea rows="2" name="goal_description" class="form-control" value="{{old('goal_description',$goal->goal_description)}}" placeholder="Enter Goal Description here ...">{{old('goal_description',$goal->goal_description)}}</textarea>
</div>
</div>
<div class="col-sm-12">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Activity<span style="color:red;">*</span></th>
<th scope="col">KPI<span style="color:red;">*</span></th>
<th scope="col">Start Date<span style="color:red;">*</span></th>
<th scope="col">End Date<span style="color:red;">*</span></th>
<th scope="col"><a class="btn btn-info addRow"><i class="fa fa-plus"></i></a></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="activity[]" class="form-control activity" ></td>
<td><input type="text" name="kpi_description[]" class="form-control kpi_description" ></td>
<td><input type="date" class="form-control start_date" placeholder="dd/mm/yyyy" name="start_date[]" min="{{Carbon\Carbon::now()->firstOfYear()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}"></td>
<td><input type="date" class="form-control end_date" placeholder="dd/mm/yyyy" name="end_date[]" min="{{Carbon\Carbon::now()->firstOfYear()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}"></td>
<td><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
</tr>
</tbody>
</table>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Weight(%):<span style="color:red;">*</span></label>
<input type="number" name="weighted_score" placeholder="Enter weighted score here" class="form-control" max="120">
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Attachment:</label>
<div class="custom-file">
<input value="{{old('appraisal_doc',$goal->appraisal_doc)}}" type="file" name="appraisal_doc" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="exampleInputFile">Choose file</label>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
</div>
</form>
AppraisalGoal is foreignkey to AppraisalGoalDetail. AppraisalGoalDetail is an Array.
The way the application operates is that, When the user clicks the submit button, the application saves into AppraisalGoal and pick its id and saves it with the other data into AppraisalGoalDetail.
However, the validation is giving issue. Whenever the user submits and the page is validated, all went blank upon showing the error page, meaning that I need to input them all over again.
I was able to resolve these ones that belong to AppraisalGoal model by using old() help function and it works:
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Title:<span style="color:red;">*</span></label>
<input type="text" name="goal_title" value="{{ old('goal_title', $goal->goal_title) }}" placeholder="Enter goal title here" class="form-control">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Goal Description</label>
<textarea rows="2" name="goal_description" class="form-control" value="{{old('goal_description',$goal->goal_description)}}" placeholder="Enter Goal Description here ...">{{old('goal_description',$goal->goal_description)}}</textarea>
</div>
</div>
I don't know how to resolve these ones that belong to AppraisalGoalDetail:
<tr>
<td><input type="text" name="activity[]" class="form-control activity" ></td>
<td><input type="text" name="kpi_description[]" class="form-control kpi_description" ></td>
<td><input type="date" class="form-control start_date" placeholder="dd/mm/yyyy" name="start_date[]" min="{{Carbon\Carbon::now()->firstOfYear()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}"></td>
<td><input type="date" class="form-control end_date" placeholder="dd/mm/yyyy" name="end_date[]" min="{{Carbon\Carbon::now()->firstOfYear()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}"></td>
<td><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
</tr>
How do I get this corrected that the page should still retain the data after submit and validation error?
Thank you
When You get Validation Error & something fault in server..You redirect the page & withInput() function like this..
return redirect()->route('goals.index')->withInput(['goal_title' => $request->goal_title, 'goal_description' => $request->goal_description]);
It will sork & show your value which you give to update

Laravel Error during update - Undefined variable: id

I am working on a project using Laravel-5.8
protected $table = 'ratings';
protected $fillable = [
'rating_type',
'rating_value',
'rating_description',
];
public function rules()
{
return [
'rating_type' => 'required|numeric|min:1|max:10|unique:appraisal_ratings,rating_type,company_id'.$this->id,
];
}
The rating has an id column, and that's the primary key. Why I checked it against company_id is that different companies can have the same rating type.
Controller
public function edit($id)
{
$rating = Rating::where('id', $id)->first();
return view('ratings.edit')
->with('rating', $rating)
->with('rating_types', $this->rating_types)
->with('rating_descriptions', $this->rating_descriptions)
->with('rating_values', $this->rating_values);
}
public function update(UpdateRatingRequest $request, $id)
{
$rating = Rating::find($id);
$rating->rating_type = $request->rating_type;
$rating->rating_value = $request->rating_value;
$rating->rating_description = $request->rating_description;
$rating->save();
Session::flash('success', 'Rating is updated successfully');
return redirect()->route('ratings.index');
}
edit.blade
<form action="{{route('ratings.update', ['id'=>$rating->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Rating:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Rating" tabindex="1" name="rating_type" style="width: 100%;">
<option value="">Select Rating</option>
#foreach($rating_types as $k => $rating_type)
<option value="{{$k}}" #if($rating->rating_type == $k) selected #endif>{{$rating_type}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Description:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Description" tabindex="1" name="rating_description" style="width: 100%;">
<option value="">Select Description</option>
#foreach($rating_descriptions as $k => $rating_description)
<option value="{{$k}}" #if($rating->rating_description == $k) selected #endif>{{$rating_description}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Rating Score:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Rating Score" tabindex="1" name="rating_value" style="width: 100%;">
<option value="">Select Rating Score</option>
#foreach($rating_values as $k => $rating_value)
<option value="{{$k}}" #if($rating->rating_value == $k) selected #endif>{{$rating_value}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('ratings.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
When I clicked on the save button to update, I got this error:
rating_type already exists.
That error should not have occured since I am doing update.
How do I resolve it?
Thank you.
You are checking the unique on update wrong
Unique Rule Usage
unique:table,column,except,idColumn
* 3rd param is for value for column to except and 4th is for column to except
Fix
//App\Http\Requests\UpdateRatingRequest
'rating_type' => 'required|numeric|min:1|max:10|unique:table_name,rating_type,table_primary_key'.$this->id,

Search function, only shows two specific people and not others in database

Using Laravel 5.8 for an assignment on CRUD cricket players and searching them.
My search function only works with one or two specific entries, the first person in my database and one I have created when I add a player.
When I search any other player by first name in the database my results page returns blank.
I have tried different conditional statements and eloquent queries.
Search form
#extends('layout')
#section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-6">
Search
<form action="/searchresults" method="POST" role="search">
{{ csrf_field() }}
<div class="form-group">
<label for="name">First Name </label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
</div>
<div class="form-group">
<label for="name">Last Name </label>
<input type="text" class="form-control" name="lastName" id="lastname" placeholder="Last name">
</div>
<div class="form-group">
<label for="age">Age </label>
<input type="number" class="form-control" name="age" id="age" placeholder="Age" value="age">
</div>
<div class="form-group">
<label for="role">Role </label>
<select class="form-control" name="role" id="role" value="role">
<option> Top-order Batsman </option>
<option> Bowler</option>
<option>Wicketkeeper batsman </option>
<option> Allrounder</option>
<option> Opening Batsman</option>
<option>Wicket Keeper Batsman</option>
<option>Middle-order Batsman</option>
<option>Batting Allrounder</option>
<option>Bowling Allrounder</option>
</select>
</div>
<div class="form-group">
<label for="batting">Batting </label>
<select class="form-control" name="batting" id="batting" value="batting">
<option>Right-hand Bat</option>
<option>Left-hand Bat</option>
</select>
</div>
<div class="form-group">
<label for="Bowling">Bowling</label>
<select class="form-control" name="bowling" id="bowling" value="bowling">
<option> Right-arm offbreak</option>
<option> left-arm fast-medium</option>
<option>Right-arm fast-medium</option>
<option> Right-arm fast</option>
<option>Right-arm medium</option>
<option> legbreak</option>
</option>Left-arm Orthodox</option>
<option>Right-arm spinoff</option>
<option> Slow left-arm Orthodox</option>
</select>
</div>
<div class="form-group">
<label for="odiRuns"> OdiRuns </label>
<input type="number" class="form-control" name="odiRuns" id="odiRuns" value="odiRuns"
placeholder="OdiRuns">
</div>
<div class="form-group">
<label for="Country">Country</label>
<select class="form-control" name="country" id="country" value="country">
<option selected valued=""> Choose...</option>
<option value="All" required>All</option>
#foreach($allcountries as $country)
<option>{{$country->name}}</option>
#endforeach
</select>
<p>(if you dont know the country please select all)</p>
</div>
<button type="submit" class="btn btn-default">Search
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
</div>
</div>
</div>
#endsection
Controller
public function search()
{
$search = request()->all();
$firstName = $search['firstName'];
$lastName = $search['lastName'];
$age = $search['age'];
$role = $search['role'];
$batting = $search['batting'];
$bowling = $search['bowling'];
$odiRuns = $search['odiRuns'];
$country = $search['country'];
$countries = Country::all();
$players = Player::query();
if (!empty($firstName)) {
$players->Where('firstName', 'like', '%' . $firstName . '%');
} elseif (empty($firstName)) {
$players->get();
}
if (!empty($lastName)) {
$players->Where('lastName', 'like', '%' . $lastName . '%');
} elseif (empty($lastName)) {
$players->get();
}
if (empty($age) || $age == 'All') {
$players->get();
} else {
$players->Where('age', $age);
}
if (empty($role) || $role == 'All') {
$players->get();
} else {
$players->Where('role', $role);
}
if (empty($batting) || $batting == 'All') {
$players->get();
} else {
$players->Where('batting', $batting);
}
if (empty($bowling) || $bowling == 'All') {
$players->get();
} else {
$players->Where('bowling', $bowling);
}
if (empty($odiRuns) || $odiRuns == 'All') {
$players->get();
} else {
$players->Where('odiRuns', $odiRuns);
}
if (empty($country) || $country == 'All') {
$players->get();
} else {
$selected = Country::where('name', $country)->get();
$players->where('country', $selected[0]->id);
}
$results = $players->get();
return view('searchresults', compact('results', 'countries'));
}
Results page
#extends('layout')
#section('content')
<table class="table">
<tr scope="row">
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Role</th>
<th>Batting</th>
<th>Bowling</th>
<th>odiRuns</th>
<th>Country</th>
<th>Player Image</th>
<th>Flag</th>
</tr>
#foreach ($results as $player )
<tr scope="row">
<td>{{$player->firstName}}</td>
<td>{{$player->lastName}}</td>
<td>{{$player->age}}</td>
<td>{{$player->role}}</td>
<td>{{$player->batting}}</td>
<td>{{$player->bowling}}</td>
<td>{{$player->odiRuns}}</td>
<td>{{$player->country->name}}</td>
<td><img src="{{ asset('images/'.$player->image) }}" class="playerimg" /></td>
<td><img src="{{asset('images/'.$player->country->flag)}}" class="flagimg" /></td>
<td>
<form method="POST" action="{{route('player.destroy',$player->id)}}">
{{csrf_field()}}
{{method_field('DELETE')}}
<button type="submit" name="deletePlayer" class="btn btn-secondary btn-md">Del</button>
</form>
</td>
<td><a class="btn btn-primary btn-md" href="{{route('player.edit',$player->id)}}" name="editPlayer"
role="button">Edit</button></td>
</tr>
#endforeach
</table>
#endsection
I would like to view certain players when searched on different aspects, like first name or last name or age, instead, I get the same two results printed the first in my database and one player I have created

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 "

Error About Laravel Blade Foreach in Loop if else

There are problem my code about foreach and if condition. When I pulled else code block out of foreach loop there are no problem it is work. But I put in else code in loop. Else dont work and dont show anything.
My purpose, programme check to used user_id in total_bonuses datatable if ok I want to display only update form if no records user_id in total_bonuses I want to show store forum and user add to info. It seems to complicated.
My controller code is below
public function show($lang=null, $id)
{
$bonuses = DB::table('reservations')
->select(DB::raw('SUM(bonus) as total_bonus, user_id'))
->where('user_id', '=', $id)
->groupBy('user_id')
->get();
$dolars = DB::table('reservations')
->select(DB::raw('SUM(dolar) as dolar, user_id'))
->where('user_id', '=', $id)
->groupBy('user_id')
->get();
$confirmeds = DB::table('reservations')
->select(DB::raw('SUM(confirmation) as confirmed, user_id'))
->where('confirmation', '=', 1)
->where('user_id', '=', $id)
->groupBy('user_id')
->get();
$user = DB::table('users')->find($id);
$totals = DB::table('total_bonuses')->where('user_id', '=', $id)->get();
return view('wallet.show', compact('totals', 'user', 'bonuses', 'dolars', 'confirmeds'));
}
View Code is below
#foreach ($totals as $total)
#if ($total->new_dollar !== NULL)
<div class="col-12"><a href="javascript:void(0)" class="link"><i class="mdi mdi-check-circle text-success"></i> <font class="font-medium"> {!! $total->new_dollar !!}
Remaining Dollar</font></a></div>
#endif
</div>
</center>
</div>
<div>
</div>
</div>
</div>
<!-- Column -->
<!-- Column -->
<div class="col-lg-8 col-xlg-9 col-md-7">
<div class="card">
#if (count($total->user_id) === 1)
<br>
<br>
<label class="col-md-12"><h4> Paid Dollar</h4></label>
<form class="form-horizontal form-material" method="POST" action="{{ route ('total.update', ['lang' => App::getLocale(), 'id' => $total->id]) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PATCH">
<input type="hidden" name='id' value='{!! $total->id !!}'>
<input type="hidden" name='user_id' value='{!! $user->id !!}'>
<div class="form-group">
<label class="col-md-12">Total Dollar</label>
<div class="col-md-12">
<input name="old_dollar" type="text" value="{!! $total->new_dollar !!}" class="form-control form-control-line" readonly>
</div>
</div>
<div class="form-group">
<label class="col-md-12">Paid Dollar</label>
<div class="col-md-12">
<input name="paid_dollar" type="text" class="form-control form-control-line">
</div>
</div>
<div class="form-group">
<label class="col-md-12">Note (Optionally! Not Required)</label>
<div class="col-md-12">
<input name="bonus_note" type="text" class="form-control form-control-line">
</div>
</div>
<input name="moderator_id" type="hidden" value="{{ Auth::user()->id }}">
<div class="form-group">
<div class="col-sm-12">
<button class="btn btn-success" type="submit">{{ __('profile.update')}}</button>
</div>
</div>
</form>
#else
<form class="form-horizontal form-material" method="POST" action="{{ route ('total.store', ['lang' => App::getLocale()]) }}">
{{ csrf_field() }}
<input type="hidden" name='user_id' value='{!! $user->id !!}'>
<div class="form-group">
<label class="col-md-12">Total Dollar</label>
<div class="col-md-12">
<input name="old_dollar" type="text" value="#foreach ($dolars as $dolar)
{{ $dolar->dolar }}
#endforeach" class="form-control form-control-line" readonly>
</div>
</div>
<div class="form-group">
<label class="col-md-12">Paid Dollar</label>
<div class="col-md-12">
<input name="paid_dollar" type="text" class="form-control form-control-line">
</div>
</div>
<div class="form-group">
<label class="col-md-12">Note (Optionally! Not Required)</label>
<div class="col-md-12">
<input name="bonus_note" type="text" class="form-control form-control-line">
</div>
</div>
<input name="moderator_id" type="hidden" value="{{ Auth::user()->id }}">
<div class="form-group">
<div class="col-sm-12">
<button class="btn btn-success" type="submit">{{ __('profile.update')}}</button>
</div>
</div>
</form>
#endif
#endforeach
Best wishes.
The problem in your provided view is with the if condition. Here you are trying to count the user id which is not possible:-
#if (count($total->user_id) === 1)
Change the above code to
#if (count($total) === 1)

Resources