Laravel - displaying categories by id - php

For a blog site, I have all the posts & lists of categories displaying on a page though now I need to display the posts for each category on it's own separate page.
Let's say I had a categorie that was 'Javascript' and I wanted only the posts with the category of javascript displayed on a page.
What's the correct code to do this? here's an example, the bold 'javascript' is what needs to be replaced with the correct code.
-- categoriesController.php ---
public function show($id)
{
$post->withCategories($Categories)->$id->($id as **javascript)**
}
--- javascript.blade.php --- ( corresponding view )
<tbody>
#foreach ($categories as $category->$id>**javascript**)
<tr>
<th>{{ $category->id }}</th>
<td>{{ $category->name }}</td>
</tr>
#endforeach
</tbody>
</table>
</div> <!-- end of .col

For example:
post.php model
class Post extends Model
{
protected $primaryKey = 'id';
function withCategories() {
return $this->hasOne('App\Categories', 'id', 'category_id');
}
public function show($id){
Post::with('withCategories')->where('category_id', $id)->get(); //the output of articles of the category
}
}
$id is a parameter of url: site.com/posts/javascript
in posts.blade.php
<table>
<tbody>
#foreach ($posts as $post)
<tr>
<th>{{ $post->id }}</th>
<td>{{ $post->name }}</td>
<td>{{ $post->withCategories->name }}</td> <!-- Category name-->
</tr>
#endforeach
</tbody>
</table>
</div>

Related

Attempt to read property "Nombre" on bool

I'm trying to make a show view with Laravel 8 but i can't show the detail, this is the code from the controller:
public function show($id)
{
$accesorios=DB::table('accesorio as acc')
->join('detalle_aparato as da','acc.idAccesorio','=','da.idAccesorio')
->select('acc.Nombre')
->where('da.idAparato','=',$id);
return view("almacen.aparato.show",["accesorio"=>Accesorio::findOrFail($id)]);
}
And this is the code from the view:
#foreach ($accesorio as $acc)
<tr>
<td>{{ $acc->Nombre}}</td>
</tr>
#endforeach
Error message
When I use:
#foreach ($accesorio as $acc)
<tr>
<td>{{ $acc}}</td>
</tr>
#endforeach
It prints: 1 for each record
Hope you can help me
In you're controller you're using DB::Table to set the $accesorios variable, but never using it.
You then are setting accesorio in your view to Accesorio::findOrFail($id) which will only return one instance of the object.
Either pass $accessorios into your view
return view("almacen.aparato.show",["accesorios"=>$accessorios]);
then loop through it
#foreach ($accesorios as $acc)
<tr>
<td>{{ $acc->Nombre}}</td>
</tr>
#endforeach
or since you're just sending one instance of the object to the view, remove the loop and you can render it like this.
<tr>
<td>{{ $accesorio->Nombre }}</td>
</tr>

How to get data from 3 tables connected with a pivot in php laravel

I faced an issue where I'm unable to retrieve data through the pivot table,
In my application there's a separate table to store the files data and a separate table to store the competition and a separate table to store the teams.
And there's a table named competition_file which has the competition_id, team_id, file_id.
a user can add multiple files to a competition by selecting a team or by not selecting a team as show in the below image
It will be synced to the competition_file table as shown in the below image
I need to show all data in the UI as a table shown in below image
I'm wondering how can I fill the team name selected using the pivot table
Relationship in File Model
public function teams()
{
return $this->belongsToMany(Team::class,'competition_file')->wherePivot('type','document');
}
Relationship in Competition Model
public function documents()
{
return $this->belongsToMany(File::class,'competition_file','competition_id', 'file_id')->wherePivot('type','document');
}
And this is my controller index function
public function index($id)
{
$competition = $this->competitionsRepo->find($id,[
'team',
'documents',
]);
return view('competitions.document',[
'competition'=>$competition,
]);
}
My Blade
#foreach ($competition->documents as $key=>$document)
<tr>
<td>{{ $key+1 }}</td>
<td>{{ $document->name }}</td>
<td>-</td>
<td>{{ $document->created_at->toDateString() }}</td>
<td>
<form class="confirm" action="{{ route('documents.destroy',['competition'=>$competition,'document'=> $document->id]) }}" method="POST"
data-confirm-title="Remove Document?"
data-confirm-message="Are you sure you want to remove this document?">
#csrf
#method('DELETE')
<button type="submit" name="button" class="button">Remove</button>
</form>
</td>
</tr>
#endforeach
Someone please help me out to get the team names to my foreach in the blade
I hope my question is clear, please comment if it isn't ill edit the question
I was able to fix my issue by learning Eager loading through a recommendation
Here are the changes I did
In controller
public function index($id)
{
$competition = $this->competitionsRepo->findOrFail($id);
$files = $competition->documents()->with(
[
'teams' => function($q) use ($competition) {
$q->with([
'documents' => function($q) use($competition) {
$q->where([
'competition_id' => $competition->id,
]);
}
]);
},
]
)->get();
return view('competitions.document',[
'id'=>$id,
'competition'=>$competition,
'files'=>$files,
]);
}
In my Blade table i used $file->teams->implode('name')
<table class="table light-td sports-tbl tb-chg2 table-condensed table-borderless">
<thead>
<tr>
<th>#</th>
<th>Document Name</th>
<th>Assigned Team</th>
<th>Date Added</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($files as $key=>$file)
<tr>
<td>{{ $key+1 }}</td>
<td>
<a href="{{ asset('storage/'. $file->file_path) }}" class="text-info" target="_blank">
<img src="{{ asset('/images/sketches/1x/file.png') }}" alt="file">
</a>
{{ $file->name }}
</td>
<td>
{!! $file->teams->isNotEmpty() ? $file->teams->implode('name') : '<span class="text-secondary">No teams selected</span>' !!}
</td>
<td>{{ $file->created_at->toDateString() }}</td>
<td>
<form class="confirm" action="{{ route('documents.destroy',['competition'=>$id,'document'=> $file->id]) }}" method="POST"
data-confirm-title="Remove Document?"
data-confirm-message="Are you sure you want to remove this document?">
#csrf
#method('DELETE')
<button type="submit" name="button" class="button">Remove</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>

laravel Property [id] does not exist on this collection instance

i cant access my admin_table i know i have and problem on my route on the admin_table please help me on my route Property [id] does not exist on this collection instance.
my admin_table.blade
#foreach ($users as $positions)
#foreach ($positions->admins as $position )
<tbody>
<tr>
<td>{{ $position->id}}</td>
<td>{{ $position->first_name}}</td>
<td>{{ $position->last_name}}</td>
<td>{{ $position->contact}}</td>
<td>{{ $position->departments->department}}</td>
<td>{{ $position->schoolpositions->school_position}}</td>
<td>{{ $position->email}}</td>
<th> Edit
</th>
</tr>
</tbody>
#endforeach
</tr>
</tbody>
#endforeach
#endforeach
</table>
this is my route
Route::get('/admin_table', 'DashboardController#index');
Route::put('/admin_table/{id}', 'DashboardController#store');
Route::get('/admin_table', 'DashboardController#show');
Route::get('/teacher_editform/{id}', 'DashboardController#edit');
Route::put('/teacher_editform/{id}', 'DashboardController#update')->name('teacheradminpage.teacher_tableform.teacher_editform');
this is my controller
public function edit($id)
{
$departments = Department::find($id);
$users = Schoolposition::find($id);
$students = Student::find($id);
$admins = Admin::find($id);
return view('teacheradminpage.teacher_tableform.teacher_editform', compact('departments','users','students','admins', 'id', 'id', 'id', 'id'));
}
Your issue is that you put an extra $position before the array. Your route should be
Edit
You've got several issues in this code that probably need attention. The main issue with the position error, seems to be that you've got a circular path to get that $position in your anchor tab within the loop.
This section is likely not creating what you want:
#foreach ($users as $positions)
#foreach ($positions->admins as $position )
This is roughly saying - take my collection of users and make a new collection of positions that are directly attached to each user object. From here, take that collection of positions and try and find a collection of admins on that are attached to that collection and then find a $position. (I think this is close to what it is trying to do...)
When you get to the inside of the loop and your anchor / route, you are asking the anchor to find an id on something that is likely either non-existent, or a collection again.
You have already passed in admins to this view. It would make sense to use that as your top level loop item, no?
To fix, use admins as the only loop item:
#foreach ($admins as $position )
Edit Your Blade With
#foreach ($users as $positions)
#if(!empty($positions->admins)
#foreach ($positions->admins as $position )
<tbody>
<tr>
<td>{{ $position->id}}</td>
<td>{{ $position->first_name}}</td>
<td>{{ $position->last_name}}</td>
<td>{{ $position->contact}}</td>
<td>{{ $position->departments->department}}</td>
<td>{{ $position->schoolpositions->school_position}}</td>
<td>{{ $position->email}}</td>
<th> Edit
</th>
</tr>
</tbody>
#endforeach
</tr>
</tbody>
#endforeach
#endif
#endforeach
</table>

How to paginate and show all records using hasMany in laravel 5.6?

I have two tables one table for general information about the order named orders and a detail table for information like products, notes and delivery date.
Basically, I want to show in the same page the table orders and for each order can be multiple products, notes, dates from the table detail, and also I want to paginate in order to show exactly 20 orders on each page and every product, note, date row with the same id_order.
In conclusion, on each page there are 20 orders from table orders but there can be 40 rows from table detail with products, notes, delivery date, because one order can contain more than one product. in fact I want to use rowspan html in order to show on the same row the detail.
This is my Orders model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class order extends Model
{
public $timestamps = false;
protected $fillable = ['client','number_order','file'];
public function details()
{
return $this->hasMany('App\Detail','orders_id')->orderBy('id', 'desc');
}
}
Detail model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Detail extends Model
{
protected $table = 'detail';
public function order()
{
return $this->belongsTo('Detail','orders_id');
}
}
My controller:
public function index()
{
$orders = Order::first(); //This works only with one record I cant show all records, all() is not working
$orders->setRelation('details', $orders->details()->paginate(10));
return view('orders.index', compact('orders'));
}
View:
<tbody>
#foreach ($orders->details as $detail)
<tr id="{{ $detail->orders_id }}">
<td>{{ $detail->product }}</td>
</tr>
#endforeach
</tbody>
You can use eager load details on order like this
public function index()
{
$orders = Order::with('details')->paginate(20);
return view('orders.index', compact('orders'));
}
In view
<table>
<tbody>
#foreach($orders as $order)
<tr>
<td>{{ $order->created_at }}</td>
<td>... put any order info here</td>
<td>
<label>Order Details:</label>
<table>
#foreach ($order->details as $detail)
<tr id="{{ $detail->orders_id }}">
<td>{{ $detail->product }}</td>
<td>{{ $detail->note }}</td>
</tr>
#endforeach
</table>
<td>
</tr>
#endforeach
</tbody>
</table>

Accessing data from a relation in blade? - Laravel

I have this code snippet in my blade:
#foreach($products as $product)
<tr>
<td></td>
<td>{{ $product->name }}</td>
<td>{{$product->tags}}</td>
<td>{{$product->created_at}}</td>
<td>
// some other code and buttons
</td>
</tr>
#endforeach
In $product->tags ( tags is the name of my relation ) are the tags I need and some other things, but I only want the tags.
I tried to reach them with $product->tags->tag but this hasn't worked for me. Can anybody tell me how I can access only the tags?
Try this:
#foreach($product->tags as $tag)
<td>{{ $tag->tag }}</td>
#endforeach
$product->tags returns an array of Tag objects.
If you have a relationship set between your Products and it's Tags (https://laravel.com/docs/5.1/eloquent-relationships)
Products Model
//namespace and use statements
class Products extends Model
{
/**
* Get all of the tags for the product.
*/
public function tags()
{
return $this->hasMany('App\Tags');
}
}
Tags Model
(assuming tags can be used for multiple products)
//namespace and use statements
class Tags extends Model
{
/**
* The tags that belong to the product.
*/
public function products()
{
return $this->belongsToMany('App\Products');
}
}
Then you can query in you controller for the products with their tags (https://laravel.com/docs/5.1/eloquent-relationships#querying-relations)
$products = App\Products::with('tags')->get();
Then you can simply access them in your view with your current code but using
#foreach($products as $product)
<tr>
<td></td>
<td>{{ $product->name }}</td>
#foreach($product->tags as $tag)
<td>{{ $tag->name }}</td>
#endforeach
<td>{{ $product->created_at }}</td>
<td>
// some other code and buttons
</td>
</tr>
#endforeach

Categories