Get objects of related tables from a collection laravel - laravel

I want to pass the result of a searching action but I am facing a problem because it is returning an array and from that all the relationships of the table are not working
result view. For this I can only access the data on my table not the related data through relationships
#extends('layouts.app')
#section('content')
#foreach ($result as $object)
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h3>Details for the animal</h3>
</div>
<div class="card-body">
<div class="col-12">
<p><strong>Id: </strong>{{ $object->id }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
#endsection
Here is my controller
<?php
namespace App\Http\Controllers;
use App\Animal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class SearchController extends Controller
{
public function index()
{
Animal::all();
return view('search.index');
}
public function postSearch(Request $request)
{
$serial_number = $request->input('search');
$this->getResult($serial_number);
return redirect()->route('result',$serial_number);
}
public function getResult($serial_number){
$result = DB::table('slaughters')->where(function ($query) use ($serial_number) {
$query->where('id','LIKE',"%$serial_number%");
})->latest()->get();
return view('search.result', ['result'=>$result]);
}
}
And my routes
Route::get('/search','SearchController#index')->name('search');
Route::post('/get','SearchController#postSearch');
Route::get('/search/{result}','SearchController#getResult')->name('result');
I would like to access data from the table related to this one too. What am to do
Slaughter model
class Slaughter extends Model
{
protected $guarded = [];
public function user(){
return $this->belongsTo(User::class);
}
public function animal(){
return $this->belongsTo(Animal::class);
}

You must create model Slaughter and define relations.
And then you can get result:
public function getResult($serial_number)
{
$result = Slaughter::with(['name_of_relation_1', 'name_of_relation_2'])->latest()->get();
return view('search.result', ['result'=>$result]);
}

In your Controller:
use App\Slaughter;
public function getResult($serial_number) {
$result = Slaughter::where('id', 'like', "%{$serial_number}%")
->with('user', 'animal')
->latest()
->get();
return view('search.result', compact('result'));
}
In your view you can then access the relationships like so:
{{ $object->user }}
{{ $object->animal }}

Related

Laravel 8 form select option dropdown problem

Am having problem here
I have two tables
Department table
with fields
id dept_code dept_name
I also have Persons table
with fields
id Persons_names Dept_name Position_held
I have a data entry form to enter data to the Persons_table
the problem am having is I want to create select option to get Dept_name From Department_table but am always getting undefined value error.
this is my form
{!! Form::open(['url' => 'persons_form/store']) !!}
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-6">
{{Form::label('FullNames', 'Fullnames')}}
{{Form::text('names', '',['class'=>'form-control','placeholder'=>'Persons Fullnames'])}}
</div>
<div class="form-group col-md-6">
{{Form::label('Department', 'Department')}}
#foreach ($depts as $dept)
{{
Form::select('department', $dept->department_name, null, ['class'=>'form-control','placeholder' => 'Select Department'])
}}
#endforeach
</div>
<div class="form-group col-md-12">
{{Form::label('Position', 'Position')}}
{{Form::text('level', '',['class'=>'form-control','placeholder'=>'Departmental Position'])}}
</div>
</div>
<div>
{{Form::submit('Save Data',['class'=>'btn btn-outline-primary text-center',])}}
</div>
{!! Form::close() !!}
this is my personsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\People;
class PeopleController extends Controller
{
public function index()
{
$depts = DB::table('departments')->select('department_name')->get();
return view('strategic_plan.people_form', ['depts' => $depts]);
}
public function create()
{
$depts = DB::table('departments')->pluck('department_name');
}
public function store(Request $request)
{
$this->validate($request,[
'names'=>'required',
'department'=>'required',
'level' =>'required'
]);
$persons =new People;
$persons->names=$request->input('names');
$persons->department=$request->input('persons');
$persons->level=$request->input('level');
$dept->save();
return redirect('/people')->with('message','Person Added Succesifully');
}
public function show()
{
$persons = People::all()->sortByDesc("id");
return view('strategic_plan.people',compact('persons'));
}
public function edit($id)
{
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
When I try to open the Form am getting
$depts is undefined
Try using compact, And get #dd in your blade of $depts and share the code.
Use
return view('strategic_plan.people_form', ['depts' => $depts]);
instead of
return view('strategic_plan.people_form', compact('depts');
write it down

Many to many relation with fk in the pivot table

i have the following structure:
Database
ingredients
id,
name
products
id,
name
ingredient_product
ingredient_id,
product_id,
ingredient_type_id
ingredient_types
id,
name
Models
Product Model
class Product extends Model
{
public function ingredients() {
return $this->belongsToMany(Ingredient::class)
->withPivot('ingredient_type_id');
}
}
Ingredient Model
class Ingredient extends Model
{
public function products() {
return $this->belongsToMany(Product::class)
->withPivot('ingredient_type_id');
}
}
My SearchController
class SearchController extends Controller
{
public function search(InitialSearchRequest $request)
{
$productsResults = Product::where('name', 'LIKE', '%' . $request['initial-search'] . '%')
->with('ingredients', 'brand')
->get();
return view('search.index')
->with(compact('productsResults'))
->with('initial-search', $request['initial-search']);
}
}
And finally my View
<div class="card-group">
#foreach($productsResults as $product)
<div class="col-sm-6 col-md-4 col-lg-4">
<div class="card"><img class="card-img-top" src="..." alt="Imagem do produto" style="width: 100%; height:100px; background-color: #696969;">
<div class="card-body">
<h5 class="card-title">{{ $product->name }}</h5>
<p class="card-text">
Important Ingredients: <br>
#foreach($product->ingredients as $ingredient)
**{{ I need here the ingredient type }}** - {{ $ingredient->name }}
#endforeach
</p>
</div>
</div>
</div>
#endforeach
</div>
So i need to show in the view my products, with the ingredients and the type of each ingredient.
This approach isnĀ“t working......
I need help to finish this task.
Thank you for any help.
You can use a pivot model:
class IngredientProductPivot extends \Illuminate\Database\Eloquent\Relations\Pivot
{
public function ingredientType() {
return $this->belongsTo(IngredientType::class);
}
}
class Product extends Model
{
public function ingredients() {
return $this->belongsToMany(Ingredient::class)
->withPivot('ingredient_type_id')
->using(IngredientProductPivot::class);
}
}
Then access it like this:
{{ $ingredient->pivot->ingredientType->name }}
As far as I know, there is no way to eager load the type relation.

How to Call/Display Foreach Loop after Login

I had problem on calling page inside Foreach Loop.Although It is Okay before I click Login, but when I'd try to login,only the html tag where loaded and foreach loop cannot... On my HomeController extends Controller
public function index()
{
return view('pages.welcome');
}
on where I call welcome page. and inside of it which is foreach loop.
<div class="row">
<div class="col-md-8">
#foreach ($posts as $post)
<div class="post">
<h3>{{ $post->title }}</h3>
<p>{{ substr($post->body, 0,300) }}
{{ strlen($post->body) > 300 ? "..." : " " }}</p>
Read More...
</div>
<hr>
#endforeach
</div>
</div>
And I think the problem is my route:
Route::get('/home', 'HomeController#index');
You haven't passed the $posts variable to the view.
Change
public function index()
{
return view('pages.welcome');
}
To something like this:
public function index()
{
$posts = \App\Post::all(); //Assuming your model is called "Post" in the App namespace
return view('pages.welcome', compact('posts'));
}
NOTE: compact('posts') is just a shortcut for ['posts'=>$posts]

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.

Fetching post comment order by in laravel

I want to fetch comment order by created at but how can i do that?
I did it as usual order by but it didnot work.
#foreach( $post->comnt->take(1)->orderBy('created_at','DESC') as $comments )
#if($post->comnt)
<div class="comments clearfix">
#foreach( $post->comnt->take(1) as $comments )
<div class="each_coments clearfix">
<p> <span class="comment_profile"><img src="{{ asset('img').'/'.$comments->user->image }}" alt=""></span></p>
<p>{{ $comments->user->username }}{{ $comments->comment }}</p>
</div><?php $last_id = $comments->id ?>
#endforeach
<a data-lastid="#if(!empty($last_id)){{$last_id}}#else{{'0'}}#endif" href="">lode more comments</a>
</div>
<?php unset($last_id); ?>
#endif
Here is my post model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
public function user()
{
return $this->belongsTo('App\User');
}
public function likes()
{
return $this->hasMany('App\like');
}
public function comnt()
{
return $this->hasMany('App\comment');
}
}
Maybe
public function comnt()
{
return $this->hasMany('App\comment')->orderBy('created_at','DESC');
}

Resources