Laravel - Property [filieres] does not exist on this collection instance - laravel

I have a little one with my school app. I want to display all the faculties of a school. Indeed in my DB a school can have one or more faculties and a faculty can belong to one or more schools.
Model School:
public function filieres ()
{
return $this->belongsToMany('App\Models\Filiere','etablissement_filieres','id_etablissements','id_filieres');
}
public function etablissement_filieres(){
return $this->hasMany('App\Models\Etablissement_filiere');
}
protected $fillable = [
'nom', 'image', 'ville', 'adresse', 'contact_1', 'contact_2',
'email', 'logo', 'presentation', 'brochure', 'localisation',
];
Model table pivot Etablissement_filiere:
public function filiere(){
return $this->belongsTo('App\Models\Filiere');
}
protected $fillable = [
'id', 'id_etablissements', 'id_filieres', 'prise_en_charge', 'prix',
];
Model Filiere:
public function etablissements ()
{
return $this->belongsToMany(Etablissement::class,'etablissement_filiere');
}
protected $fillable = [
'nom', 'diplome_requis', 'diplome_obtenu', 'prix', 'duree', 'type',
];
Controller:
public function show($id)
{
$faculty = Etablissement_filiere::where('id_etablissements','=','$id')->get();
return view('etablissements/edhec/touteslesfilieresedhec', compact('faculty','etablissements'));
}
Blade view:
#foreach($faculty->filieres as $filiere)
<div class="container bg-fil py-4 my-5">
<div class="row pl-5">
<div class="col-md-9">
<h6 class="font-weight-bold">{{ $filiere ->nom}} <br>
<span class="text-primary"> {{ $filiere ->diplome_obtenu}}</span></h6>
</div>
<div class="col-md-3 pt-n5">
<img src="{{asset($etablissement->image)}}" alt="">
</div>
</div>
<div class="row pl-5 mt-md-n5">
<div class="col-md-6">
<h6> <strong> Diplôme réquis</strong>: {{ $filiere ->diplome_requis}} <br>
<strong>Durée</strong>: {{ $filiere ->duree}} <br>
<strong>Montant de la formation</strong>: {{ $etablissement_filieres ->prix}}</h6>
</div>
<div class="col-md-6">
<h6> <strong> Mode d'etude</strong>: {{ $filiere ->type}} <br>
<strong>Prise en charge</strong>: {{ $etablissement_filieres ->prise_en_charge}}</h6>
</div>
</div>
<div class="row pl-5 mt-4">
<div class="col-md-6">
INSCRIVEZ VOUS MAINTENANT
</div>
</div>
</div>
#endforeach
I am trying to display all the faculties in the school but I have this error:
Property [filieres] does not exist on this collection instance.
Can you tell me where the error is preventing?

Your immediate view error is when it tries to evaluate $faculty->filieres.
Calls to something like Model::where()->get() return a Collection instance (which is like an iterable group) of Models, not a single Model. Even if that collection only contains one model, it's still a group and not the model itself.
So, $faculty = Etablissement_filiere::where('id_etablissements','=','$id')->get(); returns a Collection, not a single model. A single model may have a filieres property, but the Collection instance (which itself is a class in Laravel) does not. So, if what you want is the first result only, and not a collection, end that line with ->first() instead of ->get().
However even if you fix that, you also have a second problem. You're getting an instance of the pivot model Etablissement_filiere, and then trying to access the filieres property on it (which it doesn't have). Instead, you should be getting an instance of the School model. If you've defined your relations correctly, Laravel will take care of finding the pivot for you, so you normally wouldn't access a pivot model directly unless you had a particular reason to. So, instead try this in your controller:
public function show($id)
{
$establissement = Etablissement::find($id);
$faculty = $establissement->filieres;
return view('etablissements/edhec/touteslesfilieresedhec', compact('faculty','etablissement'));
}
and then in your view:
#foreach($faculty as $filiere)
There are cleaner ways to do this (e.g. look into some tutorials on route-model binding), but that should at least solve the error for your current code.

Change your code to
public function show($id)
{
$faculty = Etablissement_filiere::where('id_etablissements','=',$id)->first();
return view('etablissements/edhec/touteslesfilieresedhec', compact('faculty','etablissements'));
}

Related

Get brand name, instead of ID - Laravel 5.8

Good someone can help me, I am not doing it well. I have a table called products, in it a field called brand_id, then I have a table called brands, in which I list it by its ID field, this table also contains a column called nombre.
Model producto
class Producto extends Model
{
protected $table = 'productos';
public function marcas()
{
return $this->belongsTo(Marca::class , 'id');
}
}
Model Marca
class Marca extends Model
{
protected $table = 'marcas';
public function producto()
{
return $this->hasMany(Producto::class , 'id_brand');
}
}
Controller
public $categorias, $productos, $ofertados;
public function __construct()
{
$this->productos = Producto::with('marcas')
->latest('id')
->limit(6)
->whereEstado(1)
->get();
}
View
#foreach ($productos as $pro)
<div class="col-4 catProduct">
<div class="col-12 bordeCajon">
#if ($pro->novedad == 1)
<div class="nEntrada">NOVEDAD</div>
#endif
#if ($pro->pvpAntes == null)
#else
<div class="oferta">OFERTA!</div>
#endif
<div class="minHei">
<img src="{{ asset("{$pro->imagen}") }}" alt="">
</div>
<div class="paddingProducto">
#php
/** echo "<pre>"; print_r($pro->marcas);*/
#endphp
<h2> {{ $pro->marcas->mombre }} </h2>
<h3>{{ $pro->producto }}</h3>
<div class="dividerProd"></div>
<h4>{{ $pro->pvpAhora }} <span>€</span></h4>
#if ($pro->pvpAntes == null)
#else
<div class="pvpAntes">{{ $pro->pvpAntes }} <span>€</span></div>
#endif
VER PRODUCTO
</div>
</div>
</div>
#endforeach
Error
Trying to get property 'nombre' of non-object (View: /Applications/MAMP/htdocs/camasLiteras/resources/views/index.blade.php
For example, in the marks table I have 4 marks. In the beginning I have 6 products each with a brand. Well it does what we have done is take the product and put the name of the brand in the same order of the brand table, that is, it does not put the name that it touches. And since there are 6 products but only 4 brands, that's why it says the 'name' of no-object '. If I deactivate two products it doesn't give me an error but it shows in each product a different brand, putting the 4 there are.

How to send variable from blade to controller without changing the url

In blade I have a list of books. I want to choose a specific book to show its information. And to do so I want to send with href the id of the book to my controller passing through route.
For example i have
<div class="body text-center">
<h6><b>{{($book->getName())}}</b></h6>
</div>
In href I want to add $bookId = $book->id and the route name so I can call the route with the specific name which calls a method in a controller which can use the variable $bookId
Route::get('/infromation','Books\BookController#index')->name('info');
Here's two propositions:
The first one is to use spatie/laravel-sluggable to have the book name in the URL
The second one is to access the book without changing the URL with a POST request
Using spatie/laravel-sluggable
The slug will be generated automatically from name when the book is created.
your-migration.php
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('slug')->unique()->index();
$table->string('name');
// ...
$table->timestamps();
});
web.php
// Change the URIs as you want. `{book}` is mandatory to retrieve the book though.
Route::get('/books','Books\BookController#index')->name('book.index');
Route::get('/books/{book}','Books\BookController#show')->name('book.show');
Book.php
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class Book extends Model
{
use HasSlug;
protected $guarded = [];
public function getSlugOptions()
{
// Adapt with what you want
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug')
->doNotGenerateSlugsOnUpdate();
}
public function getRouteKeyName()
{
return 'slug';
}
}
BookController.php
class BookController extends Controller
{
public function index()
{
return view('book.index');
}
public function show(Book $book)
{
// $book is retrieving using Model Binding: https://laravel.com/docs/5.8/routing#route-model-binding
return view('book.show', compact('book'));
}
}
index.blade.php
<div class="body text-center">
<a href="{{ route('book.show', $book) }}">
<h6><b>{{ $book->getName() }}</b></h6>
</a>
</div>
Using POST request (URI does not change) and without SLUG
I wouldn't recommend using this for the user experience.
The user cannot bookmark the book or share the link with someone else
When refreshing the page, it will prompt to the user if he want to re-submit the form request
web.php
Route::get('/books','Books\BookController#index')->name('book.index');
Route::post('/books','Books\BookController#show')->name('book.show');
BookController.php
class BookController extends Controller
{
public function index()
{
return view('book.index');
}
public function show()
{
$book = Book::findOrFail(request('book_id'));
return view('book.show', compact('book'));
}
}
index.blade.php
<div class="body text-center">
<form action="{{ route('book.show') }}" method="POST">
#csrf
<input type="hidden" value="{{ $book->id }}" name="book_id">
<h6>
<button type="submit">
<b>{{ $book->getName() }}</b>
</button>
</h6>
</form>
</div>
You can remove the default button style to make it looks like a link
https://stackoverflow.com/a/45890842/8068675
You can try like this
<form action="/BookName/information/<?php echo $book->id; ?>" method="post">
<div class="body text-center">
<input type="hidden" name="book_id" value="{{ $book->id }}">
<a href="/information/<?php echo $book->id; ?>">
<button type="submit" name="book_information" class="btn btn-primary">
<h6>
<b>{{($book->getName())}}</b>
</h6>
</button>
</div>
</form>
// make route like this
Route::post('/BookName/information/{id}','Books\BookController#index');
// Access the that id in controller
public function index(Request $request)
{
echo $request->book_id;
}

How to show data in blade by id

I have to make a website for student hostels in my country I have a special page for every hostel that shows its all photos and property but I don't know how can I do this with the hostel id when I have a hostel table if someone can help me, please!
thank's for all
This is my hostel controller code:
class HostelDetailsController extends Controller
{
public function index(Request $request,$detail_id)
{
// $id = $request->query($detail_id);
$file_details = HostelDetails::all();
$files = Attachment::get();
return view('khabgah_details', compact(['file_details', 'files']));
}
}
This is my hostel page blade code:
#foreach($file_details as $file)
<div class="card-title text-center">
<div class="mt-4"></div>
<i class="fa fa-home mt-4 text-center" style="font-size:45px;"></i>
<h5 class="mt-3 text-center"> لیلیه نرگس </h5>
<h6 class="fa fa-phone"> شماره تماس: {{ $file->phone_number }} </h6>
</div>
#endforeach
It doesn't show any error message but when I load the page it shows all my records in the table
//You can get the id from the index page of the hostel
public function show($id)
{
$details = Detail::where('hostel_id', '=', $id)->get();
return view('HostelDetailPage',compact('details'));
}

get category name in a post record

I have a list containing article posts from all categories. I want to display the category tag in each post on the list and I tried this :
<article class="post bg z-depth-1">
<?php foreach ($article_list as $article): ?>
<div class="post-img">
<a href="post.html">
<img class="retina" src="{{ asset('image/' . $article->image) }}" width="820" height="500" alt="Post Image">
</a>
</div>
<div class="post-content">
<div class="post-header center-align">
<div class="tags">
{{ $article->category->title }}</div>
<h2 class="post-title">{{ $article->title }}</h2>
<div class="date">Posted on {{ Carbon\Carbon::parse($article->created_at)->format('F j, Y') }}</div>
</div>
<div class="post-entry">
<p>sss</p>
</div>
<div class="post-footer">
<div class="post-footer-item">
<span class="text">Read More</span> <i class="fa fa-arrow-circle-right"></i>
</div>
</div>
</div><!-- .post-content -->
<?php endforeach ?>
</article><!-- .post -->
and it gave me error Undefined property: stdClass::$category and I don't know why, I already define the relationship in each model Article and Category. Thanks for the help!
In Article model :
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
In Category model :
public function article() {
return $this->hasMany('App\Article', 'category_id');
}
Controller :
public function index() {
$article_list = Article::all();
return view('article/index', compact('article_list', $article_list));
}
What you need to do is eager load those relationships in your controller.
When you pull the records do it like this:
$article_list = Article::with('category')->get();
https://laravel.com/docs/5.3/eloquent-relationships#eager-loading
Change this: $article->category->title
To this: $article->category()->title
When you define the relationship in your model you are also creating a function not a property called category.
public function category()
{
return $this->belongsTo('App\Category');
}
In Category model :
public function article() {
return $this->hasMany('App\Article');
}
Controller :
public function index() {
$article_list = Article::all();
return view('article/index', compact('article_list'));
}
This should work for you now like this.

Laravel 4 - Many to Many - pivot table not updating

I get no obvious errors when adding a new job to my database.
My industry job goes into the jobs table but the relationship with divisions in my join table goes nowhere. I just can't see where I'm going wrong
JOIN TABLE
division_industryjob
division_id
industryjob_id
divisions
id
division_name
industryjobs
id
job_title
MODELS
Division.php
<?php
class Division extends \Eloquent {
protected $table = 'divisions';
/**
* Industry Jobs relationship
*/
public function industryjobs()
{
return $this->belongsToMany('IndustryJob');
}
}
IndustryJob.php
<?php
class IndustryJob extends \Eloquent {
protected $table = 'industryjobs';
public function divisions()
{
return $this->belongsToMany('Division');
}
}
ROUTES
Route::get('industry-jobs/add', 'AdminController#getCreateIndustryJob');
Route::post('industry-jobs/add', 'AdminController#postCreateIndustryJob')
CONTROLLER
// Create Industry - Get (empty form - new entry)
public function getCreateIndustryJob()
{
View::share('page_title', 'Create a new Industry Job Role');
View::share('sub_page_title', 'Ex: Mechanical Technician');
return View::make('admin/industry-jobs/create');
}
// Create Industry - Post
public function postCreateIndustryJob()
{
//validate user input
$rules = array(
'job_title' => 'Required|Min:3|Max:80'
);
$validation = Validator::make(Input::all(), $rules);
If ($validation->fails())
{
return Redirect::to('/admin/industry-jobs/add')->withErrors($validation);
} else {
$industryjob = new IndustryJob;
$industryjob->job_title = Input::get('job_title');
$industryjob->job_description = Input::get('job_description');
$industryjob->job_qualifications = Input::get('job_qualifications');
if (isset($input['divisions'])) {
foreach ($input['divisions'] as $divId) {
$div = Division::find($divId);
$industryjob->divisions()->save($div);
}
}
$industryjob->save();
return Redirect::to('/admin/industry-jobs')->with('message', 'Industry Job created successfully');
}
}
FORM
<form class="form-horizontal" method="post" autocomplete="off">
<!-- Industry Job Title -->
<div class="form-group">
<label class="col-md-2 control-label" for="industry_name">Industry Job Title (*)</label>
<div class="col-md-10">
<input class="form-control" type="text" name="job_title" id="job_title" value="" />
</div>
</div>
<!-- ./ Industry Job Title -->
<!-- Industry Type -->
<div class="form-group">
<label class="col-md-2 control-label" for="body">Related Division</label>
<div class="col-md-10">
<select name="divisions[]" id="divisions" size="6" class="form-control" multiple>
#foreach (Division::all() as $division)
<option value="{{ $division->id }}" >{{ $division->division_name }}</option>
#endforeach
</select>
</div>
</div>
<!-- ./ Industry Type -->
<!-- Form Actions -->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-success">Create Job</button>
</div>
</div>
<!-- ./ form actions -->
</form>
You are saving the Parent model afterwards so it's not working. Save the Parent model before you save the Child Model, so it should be something like this:
$industryjob = new IndustryJob;
$industryjob->job_title = Input::get('job_title');
$industryjob->job_description = Input::get('job_description');
$industryjob->job_qualifications = Input::get('job_qualifications');
$industryjob->save();
Then save the related models using sync because it's many-to-many relationship and those related models are already created and available in the database:
if (isset($input['divisions'])) {
// Pass the array of ids to sync method
$industryjob->divisions()->sync($input['divisions']);
}
If you use the foreach loop then you may use something like this;
foreach ($input['divisions'] as $divId) {
$industryjob->divisions()->attach($divId);
}
Check more about inserting related models on Laravel website.

Resources