Laravel 4 search function validation - laravel

I've got an problem.
How could I validate an search function? Like if it fails to find the user, it'll display an error message. I've tried several things, but none of them works. Here's my form:
(search/search.blade.php)
<form id="custom-search-form" class="form-search form-horizontal pull-right" action="{{ URL::action('CharactersController#search') }}" method="get">
<div class="input-append span9">
<input type="text" class="search-query" name="character" placeholder="Character/guild name">
<button type="submit" class="btn"><i class="icon-search"></i></button>
</div>
I've tried to do something like: #if ($searchResult->count()) - it works, but it displays every time I enter the search site.
Here's my controller's acction:
public function search()
{
$name = Input::get('character');
$searchResult = Player::where('name', '=', $name)->get();
return View::make('search.search')
->with('name', $name)
->with('searchResult', $searchResult);
}

Shouldn't it be
#if(count($searchResult) > 0)
//Show results?
#endif

You could split your controllers methods into getSearch() to display the search form and then use postSearch() to display the results.
public function getSearch()
{
return View::make('search.search');
}
public function postSearch()
{
$name = Input::get('character');
$searchResult = Player::where('name', '=', $name)->get();
return View::make('search.search')
->with('name', $name)
->with('searchResult', $searchResult);
}
//search.blade example
#if(isset($searchResult))
#if($searchResult->count() > 0)
//display results
#else
//no results to display
#endif
#endif

Related

Undefined variable: foods

hi guys am in need of assistance , i know this seems to be an easy one but am a bit confused , i have a foreach loop in my main.blade.php file, which shows foods from my database it works fine but when its clicked it meant to lead to the individual post and thats where i get the error
Undefined variable: foods
heres my foreach loop in main.blade.php file
#foreach($foods as $food)
<li class="item">
<a href="{{ route('Foods.show', $food->id) }}">
<img src="{{ Storage::disk('local')->url('food_images/'.$food->image ) }}" class="img-responsive w-25 p-3" alt="Food" >
<div class="menu-desc text-center">
<span>
<h3> {{ $food->title }}</h3>
{{ $food->body }}
</span>
</div>
</a>
<h2 class="white"> #{{ $food->price }}</h2>
</li>
#endforeach
heres my main.blade.php controller
public function LoadHome()
{
$foods = Food::all();
$foods = Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get();
return view('pages.home')->withFood($foods);
}
and heres Foods.show controller function
public function show($id)
{
$foods = Food::Find($id);
return view('foods.show')->withFood($foods);
}
please what am i doing wrong
Have you tried passing data from your controller to the view using this something like this:
public function show($id)
{
$foods = Food::Find($id);
return view('foods.show')->with('foods', $foods);
}
or, if you're passing multiple variables to the view:
public function show($id)
{
$foods = Food::Find($id);
$something = "else";
return view('foods.show', compact('foods', 'something'));
}
Your view doesn't know what $foods is at that point, so it's always good practice to check that foods is set before the loop:
#if (isset($foods) && $foods->count() > 0)
#foreach($foods as $food)
...
#endforeach
#endif
See the official Laravel docs for more information.
If you want the variable to be named foods in the view then you would need to use withFoods not withFood:
return view(...)->withFoods($foods);
As mentioned in the other answers, there are other ways to pass data to the views as well.
There is no data being passed to a view.
This is how you pass data to a view:
public function LoadHome()
{
$foods = Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get();
return view('pages.home', ['foods' => $foods])
}
If you always want to have $foods in main.blade.php you should place this in a service provider
View::share('foods', Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get());
https://laravel.com/docs/7.x/views#sharing-data-with-all-views

Get data from three models with relationship laravel

I have three models :
Serie ($id)
public function saisons()
{
return $this->hasMany(Season::class);
}
public function episodes()
{
return $this->hasManyThrough(Episode::class, Season::class);
}
Season ($serie_id)
public function serie()
{
return $this->belongsTo(Serie::class);
}
public function episodes()
{
return $this->hasMany(Episode::class);
}
Episode ($season_id)
public function season()
{
return $this->belongsTo(Season::class);
}
public function serie()
{
return $this->BelongsToThrough(Serie::class, Season::class);
}
I would like to show one specific season from a serie with the episodes associated
My view
<h1 class="title">{{$serie->seasons->number}}</h1>
#foreach ($serie->seasons->episodes as $episode)
<div class="row">
<div class="columns">
<div class="col">
{{$episode->number}}
{{$episode->name}}
#if(isset($episode->programmation->date))
{{$episode->programmation->date}}
#endif
#if (($episode->season_finale) == '0')
Non
#elseif (($episode->season_finale) == '1')
Oui
#endif
#foreach ($episode->chaines as $chaine)
{{$chaine->name}}
#endforeach
</div>
</div>
</div>
#endforeach
Route
Route::get('/serie/{serie}/saison/{season}', 'Front\SaisonController#show')->name('saison.show');
For my url, I choose to show the number of the saison and not the id and I think that's the problem.
How can I do that in a proper way ?
I think this approach can help you.
$serie = Serie::where('id',$id)->with('seasons'=>function($query) use ($season_id) {
$query->where('season_id',$season_id)->with('episodes')->get();
})->get();
Ok, someone help me to find the right answer :
$serie = Serie::findOrFail($serie);
$season = Season::where('serie_id', $serie->id)->where('season.number', $season)->first();

how do i pass data value to another page via link in laravel?

i am trying to make a list of locations that you can rent. but to rent the place you need to fill in some information. to fill in this information you excess another page. how do i make it so laravel knows the page belongs to a certain location
this is what ive done now but i keep getting the error:
Call to undefined method App\Reservation::location()
as soon as i have filled in the fields of information
this is the blade file that links to the the create reservation file
#foreach
($locations as $location => $data)
<tr>
<th>{{$data->id}}</th>
<th>{{$data->name}}</th>
<th>{{$data->type}}</th>
<th><a class="btn" href="{{route('Reservation.index', $data->id)}}">rent</a></th>
</tr>
#endforeach
this is the create reservations blade
<form action="{{ route('location.store') }}" method="post">
#csrf
<label>title</label>
<input type="text" class="form-control" name="name"/>
<label>type</label>
<select>
<option value="0">klein</option>
<option value="1">groot</option>
</select>
<button type="submit" class="btn">inschrijven</button>
</form>
this is what the location controller looks like
public function store(Request $request)
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($request->location());
$location->save();
return redirect('/location');
}
and the relationships in my models should also work
class Reservation extends Model
{
public function locations()
{
return $this->belongsTo('Location::class');
}
}
class Location extends Model
{
public function reservations()
{
return $this->hasMany('Registration::class');
}
}
ive been stuck at this all day and i really dont know where to look anymore
The error you are getting is because of the wrong function name, you are calling location, while it is locations.
public function locations(){}
&
$location->location()->associate($request->location());
and you can pass the variable as a query parameter, you'll need to pass this data as an array in your blade file.
Web.php
Route::get('/somewhere/{id?}, function(){
//do something
})->name('test');
Blade
route('test', ['id' => $id]);
Controller Method
public function store(Request $request, $id) //Adding the query parameter for id passed in Route.
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($id);
$location->save();
return redirect('/location');
}

How to update image file in laravel?

I am trying to update an image of a database (One-To-Many and Belongs-To Relationships)
i have table proposition with fields id, proposition.
now the proposition table has relations with image table like this
image module
public function proposition()
{
return $this->belongsTo('App\Proposition');
}
proposition module
public function propositionimage() {
return $this->hasMany('App\PropositionImages');
}
now i want to update the image to an proposition:
i want to get the old value of input file and change it with the new value of input file .
the probleme is whene i use this
$proposition = Proposition::find($num_proposition);
$image = $proposition->propositionimage()->get();
it showing all the image of the proposition
i want to update all the image but one by one , any help plz ?
the HTML code
<img src="/images/{{ $propositonimage->imagename }}" alt="">
<div class="caption">
<input type="file" name="image" value="{{$propositonimage->imagename}}" >
</div>
the update function
public function update(PropositionRequest $request, $num_proposition)
{
$proposition = Proposition::find($num_proposition);
$image = $proposition->propositionimage()->get();
// echo "$image";
$images = Input::file('image');
if (Input::hasfile('image')) {
$rules2 = array('image' => 'mimes:jpeg,bmp,png');
$validator2 = Validator::make($images, $rules2);
if ($validator2->passes()) {
$distinationPath = 'images';
$imagename = $images->getClientOriginalName();
$upload_success = $images->move($distinationPath, $imagename);
$extension = $images->getClientOriginalExtension();
}
}
Im not 100% sure what the problem is. But it seems as you want to iterate the collection over the div?
proposition model
public function propositionimage()
{
return $this->hasMany(PropositionImages::class);
}
image model
public function proposition()
{
return $this->belongsTo(Proposition::class);
}
Then you return a view with proposition in a controller, and eager load PropositionImages?
public function index(){
$propositions = \Proposition::with('propositionimage')->get();
return view('image', compact('propositions'));
}
You will have a collection of proposition with corresponding images.
#forelse ($propositions as $propositon)
<img src="/images/{{ $propositon->imagename }}" alt="">
#if($propositon->propositionimage->count())
<div class="caption">
#foreach($propositon->propositionimage as $propositionimage)
name: {{$propositionimage->imagename}}<br>
<input type="file" name="image" value="{{$propositionimage->imagename}}" >
#endforeach
</div>
#else
No proposition image <br>
#endif
#empty
No images :(
#endforelse
Please add more details to your question otherwise.
Edit
I tried this at my local dev machine and it works.
All relations of propositionimage will be iterated to the corresponding proposition.

laravel 5.3 old input values always empty

see docs here about old input
Route::post('/search/all/', function (Request $request) {
//...
$products = $query->paginate(15);
$data = ['products' => $products,
'oldinput' => $request->all()];
return view('inventory.search_products', $data);
});
in the view:
this works:
<input type="text" id="search_all" name="search_all" value="{{ $oldinput['search_all'] }}">
this is always empty:
<input type="text" id="search_all" name="search_all" value="{{ old('search_all') }}">
Just call flush in your controller then you can use old() helper function in your blade.
public function YourController(Request $request){
$request->flash();
return view('yourblade');
}
In blade file:-
<input id="lng" name="lng" value="{{old('lng')}}" type="hidden">
docs says you should flash() then call old() method.
flashing stores the previous request in the session. so it makes sense that old(search_all) doesn't work
I will suggest the following solution:
return view('inventory.search_products', $data)->withInput(\Input::all());
And in blade you can call as well \Input::old('search_all');.

Resources