Laravel: Get softdeleted row in a query builder consult - php

How do I get a row that was sofdeleted for example
This is my code:
$mov = $emp->movimientos()->where('movimiento.linea_id', intval($request->id_caso))->with('producto_nombre', 'costo_promedio');
I have this consult, one movimientos is related with a costo_promedio, but if in some case acosto_promedio is softdeleted the result in my consult $mov will give me null in the part of costo_promedio.
The thing is, where do I have to puth the withTrashed() method to get all data even the ones that were softdeleted
Thx for the help

Use with() with a closure:
$mov = $emp->movimientos()
->where('movimiento.linea_id', intval($request->id_caso))
->with([
'producto_nombre',
'costo_promedio' => function($query) {
$query->withTrashed();
}
]);

you can call withTrashed() function anywhere in 'Eloquent Query Builder' instance, but before get() or first() finction.
to eager load relationship with trashed, you can give a closure to the relationship.
$mov = $emp->movimientos()->where('movimiento.linea_id', intval($request->id_caso))
->with([
'producto_nombre',
'costo_promedio' => function($q) {
$q->withTrashed();
}
])->get();

Related

Search many level Eloquent Collection

If I have a collection with many levels, are there any tricks to find out what I need to put in my where() to be able to search by it? This is what I have so far, but I get an empty array from it. $contacts->where('contacts.tags.id', $tag->id) I've also tried contacts.tags.tags.id This is what I get if I run dd($contacts)
You may be looking for Eloquent - Eager Loading With Constraints.
$id = 'Your ID you are searching for';
$contacts= App\Models\Contact::with(['tags' => function ($query) {
$query->where('id', '=', $id');
}])->get();
show me all the contacts where tags = id. if it's only one you may switch ->get() for ->first() to return the object instead of a collection (array)

Eloquent | Using with() resulting in NULL bring returned

I am trying to use Eloquent in Laravel in order to run a query. I am using the with() function in order to get the results from relationships, however this is always returning null.
This is my code:
Posts::query()
->select('id')
->with([
'author:id',
'category.images:url',
]);
Dumping the query using the getQueryLog() function and if I run the query inside of a SQL client with the same bindings I get a result back, however the response looks like this...
{
id: 1,
category: {
id: 1,
category_images: null
}
}
I've tried googling this issue and can't really find anything on it.
Thanks in advance.
Use your query like this:
Posts::query()->select('id')->with([ 'author', 'category' ])->get();
and in Posts model
public function author()
{
return $this->belongsTo('Authors::class', 'author_id', 'id')->select('id');
}
public function category()
{
return $this->belongsTo('Categories::class', 'category_id', 'id')->select('id', 'images.id', 'images.url');
}
You have to select your foreign keys in select statement to let Eloquent query your relationships, something like this:
Posts::query()
->select('id', 'author_id', 'category_id')
->with([
'author:id',
'category.images:url',
]);

Laravel 5.3 Pagination - ErrorException in Collection.php line 432

Every time I try to setup my pagination:
Missing argument 1 for Illuminate\Support\Collection::get()
My controller:
public function index()
{
$products = DB::table('products')
->where('product_group_id', '=', 1)
->paginate(15)
->get();
return view('product.index', [
'products' => $products,
]);
}
My view:
{{ $products->links() }}
What goes wrong here?
You don't need ->get() here. ->paginate() gets your records from the database and returns a collection of those 15 items.
When you're running ->get() here you're attempting to run it on the collection that is returned which expects a $key and is used to get a specific item out of a collection.
You should do this:
$products = DB::table('products')
->where('product_group_id', '=', 1)
->paginate(15);
return view('product.index', [
'products' => $products,
]);
or with Eloquent
$product = Product::where('product_group_id', '=', 1)
->paginate(15);
return view('product.index', [
'products' => $products,
]);
Note: I have put the filters before the paginate() call to ensure that the where clause is part of the database query rather than trying to filter the resulting collection/paginator
When you call the paginate() method on a Illuminate\Database\Query\Builder object, You will get an instance of \Illuminate\Pagination\LengthAwarePaginator. That itself does not have a get()-Method, but the Illuminate\Pagination\AbstractPaginator it extends has a magic __call() function which forwards the call to the underlying Collection.
Now, Illuminate\Support\Collection does have a get() method, but it takes the key of the element you want to get out of the Collection as an argument, hence the error you get.
Now, I suppose what you actually want to achieve standard pagination with links for page numbers and "forward" and "back" buttons. If so, you should just stick to the documentation: Get the data just the way you did, just leave out the get(), then display it in a view the way its shown here.
EDIT: Just read about the Method links does not exist error you get. That is indeed strange. Builder::paginate() definitely returns an Instance of LengthAwarePaginator which itself definitely has a links() method.
Is there perhaps some more code that is relevant to this problem which you havent shown us yet? Maybe in your view?

Laravel 5.2 : Fetch records against logged in user id

I am fetching records in controller :
$tasks = Task::where('user_id', '=', Auth::user()->id);
return view('todo',compact('tasks'));
But it returns null.
And Auth::user()->id returns 2 Which is Okay.
Am i missing something ?
You need to actually retrieve the record. What you have is an instance of \Illuminate\Database\Eloquent\Builder, but not the actual record(s) associated with the query.
To tell Eloquent to fetch the data, you need to use either get().
Like:
$tasks = Task::where('user_id', '=', Auth::user()->id)->get();
As a side note, you can simplify your query to be:
$tasks = Task::where('user_id', Auth::user()->id)->get();
Furthermore, on your User model, you could do this:
public function tasks()
{
return $this->hasMany(Task::class) // make sure you use the full namespace here or use at the top of User.php
}
And then you can simply do:
$tasks = auth()->user()->tasks;
This is a Relationship in Eloquent as explained in the docs.

Laravel fetch data from model where the condtions is from another model

I have a table called List which i planned to be displayed into view with this command : $lists= List::with('user', 'product.photodb', 'tagCloud.tagDetail')->get();. But, i want the data displayed is only those that has TagID equal to the one user inputted. Those data can be retrieved from TagCloud table.
What i am currently doing is :
$clouds = TagCloud::select('contentID')
->where('tagDetailID', '=', $tagID)
->get();
$lists = List::with('user', 'product.photodb', 'tagCloud.tagDetail')
->where('id', '=', $clouds->contentID)
->get();
But when i tried to run it, it only return a null value, even though when i am doing return $clouds, it does returned the desired ID.
Where did i do wrong ? Any help is appreciated !
A couple of gotchas with your current solution.
Using get() returns an Illuminate\Database\Eloquent\Collection object. Hence you can't use $clouds->contentID directly since $clouds is a collection (or array if you prefer). See Collection Documentation.
where(...) expects the third parameter to be a string or integer, aka single value. Instead, you are passing a collection, which won't work.
The correct way is to use whereHas() which allows you to filter through an eager loaded relationship.
Final Code:
$lists = List::with('user', 'product.photodb', 'tagCloud.tagDetail')
->whereHas('tagCloud',function($query) use ($tagID) {
return $query->where('contentID','=',$tagID);
})
->get();
See WhereHas Documentation.
What you want is whereHas()
$list = List::with(...)
->whereHas('relation', function($q) use($id) {
return $q->where('id', $id);
})->get();
Apply Where condition in you tagCloud model method tagDetail
public function tagDetail(){
return $q->where('id', $id);
}

Categories