Get data from three models with relationship laravel - 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();

Related

Laravel Accessing Attributes & Slots Within Component Classes

I have a question about Laravel - Documentation - Accessing Attributes & Slots Within Component Classes
I read this section, and did some experiments. What I've found is that the closure only can return string but component.view, and what it returns would overwrite what is defined on the component view, which leads me to a question What use case is this feature for?
Could anyone make some examples of using this feature for me?
Anyone could help me with it will be so much appreciated.
If the string matches an existing view then it will render that view and not overwrite it. You can return an existing view as follows:
// app/View/Components/Post.php
public function render()
{
return function (array $data) {
// $data['componentName'];
// $data['attributes'];
// $data['slot'];
return 'components.post'; // /resources/views/components/post.blade.php
};
}
// views/components/post.blade.php
<div class="item">
<div class="title">
New Post
</div>
<div class="content">
<p>Content post...</p>
</div>
</div>
Example:
// component class
class Link extends Component
{
public $path = "";
public function __construct()
{
$this->path = request()->path();
}
public function render()
{
return function (array $data) {
if(isset($data['attributes']['href'])) {
$data['attributes']["link"] = $data['attributes']['href'];
if ($data['attributes']['href'] == "/".$this->path) {
$data['attributes']['active'] = $data['attributes']['class']." link-active-class";
} else {
$data['attributes']['active'] = $data['attributes']['class'];
}
}
return 'components.commons.link';
};
}
}
// component view
<a href="{{ $attributes['link'] }}" class="{{ $attributes['active'] }}">
{{ $slot }}
</a>
Usage:
<x-commons.link href="/module/news" class="primary-action">
<i class="fas fa-newspaper"></i> News
</x-commons.link>

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

Laravel- Handling multiple checkboxes in pivot tables

I have been struggling with this for a while, am a new developer with very little experience. So am working on a project dealing with drugs and diseases. There exists a many to many relationship.
Drug model
public $timestamps=false;
public function disease()
{
return $this->belongsTo('App\Disease');
}
Disease model
public $timestamps=false;
public function drug()
{
return $this->belongsTo('App\Drug');
}
I want to create relationships in the Disease_Drug pivot table using forms.
form.blade.php
<label>Disease</label>
<select class="form-inline input-sm " name="disease" id="disease">
#foreach($diseases as $key => $disease)
<option value="{{$disease->id}}"> {{$disease->name}}</option>
#endforeach
</select>
<label>Drugs</label><br>
#foreach($drugs as $key=>$drug)
<input type="hidden" name="drug[]" value="0" />
<input class="checkbox-inline" type="checkbox" name="drug[]"value="{{ $drug->id }}" id="{{ $drug->id }}">{{ $drug->name }} <br>
#endforeach
<button type="submit" class="btn btn-primary">Submit</button>
I have a disease_drug controller
public function form()
{
$diseases = Disease::all();
$drugs = Drug::all();
return view('admin.form')
->with('diseases', $diseases)
->with('drugs', $drugs);
}
public function store(Request $request)
{
$diseases = $request->get('diseases.ids');
$drugs = $request->get('drugs.id', []); // Empty array by default if no checkbox checked.
$diseases->drugs()->sync($request->input('drugs', []));
}
I am unable to save the results in the database. I am really clueless on this so kindly help me out.
If relation between drugs and disease is Many To Many then your relation function should be as:
Drug model
public function disease()
{
return $this->belongsToMany('App\Disease');
}
Disease model
public function drug()
{
return $this->belongsToMany('App\Drug');
}
You are using belongsTo() function instead.

Laravel 4 - Method[ ] does not exist

I'm still a novice to Laravel 4 and trying to figure out why I'm getting an error saying that Method [inventoryNotFound] does not exist. It has to do when I am attempting to use the InventoryController#show function.
On my Index page I have a href that I'm trying to send to the show views. The code looks like this:
#foreach($inventory as $item)
<div class="col-md-4 inventory">
<img class="img-responsive" src="{{{$item->image}}}">
<a class="description" href="">{{{$item->title}}}</a>
#foreach($item->size_details as $details)
<p>{{ $details->size }}: {{ $details->price }}</p>
#endforeach
</div>
#endforeach
My show function is:
class InventoryController extends BaseController {
public function index()
{
$inventory = Inventory::all();
return View::make('inventories.index')->with('inventory', $inventory);
}
public function show($id)
{
$inventory = Inventory::find($id);
if(is_null($inventory)){
return $this->inventoryNotFound();
}
return View::make('inventories.show',['inventory' => $inventory]);
}
}
And I have a resource controller as my routes:
Route::resource('inventories', 'InventoryController');
Even when I attempt to run my routes manually, I run into the same problem.
Any ideas as to why?

Laravel 4 search function validation

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

Resources