So I am trying to attach an object full of information from the MYSQL DB, but the outcome isn't what I am expecting.
Controller -
public function index()
{
$location = Location::orderBy('created_at', 'desc');
return view('location')->with('locations', $location);
}
Model -
class Location extends Model
{
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;
}
Result -
Builder {#486 ▼
#query: Builder {#485 ▶}
#model: Location {#484 ▶}
#eagerLoad: []
#localMacros: []
#onDelete: null
#passthru: array:12 [▶]
#scopes: []
#removedScopes: []
}
Change this
$location = Location::orderBy('created_at', 'desc');
To
$location = Location::orderBy('created_at', 'desc')->get();
When using $location = Location::orderBy('created_at', 'desc'); it is a instance of Illuminate\Database\Query\Builder.
For get all records you must use
$locations = Location::orderBy('created_at', 'desc')->get();
It is return instance of \Illuminate\Database\Eloquent\Collection
For get Limited records you must use
$limit = 20; // or custom
$limitedLocations = Location::orderBy('created_at', 'desc')->limit($limit)->get();
For get single data use
$location = Location::orderBy('created_at', 'desc')->first();
It is return null or instance of model Location
Related
I'm trying to get datas from a persistent collection in a ManyToMany relation.
$form = $this->formRepository->find($id);
dd($form->getAssocies());
give me something like :
Doctrine\ORM\PersistentCollection {#2558
-snapshot: []
-owner: App\Entity\Form {#2617
-id: 174
-name: "Aname"
-category: Proxies\__CG__\App\Entity\Category {#2554
+__isInitialized__: false
-id: 30
-name: null
-children: null
-parent: null
...
when I try this :
$form->getAssocies()->toArray();
it return me an empty array, same result with a ->getValues()
I also tried this :
foreach ($form->getAssocies() as $key => $associe) {
$data['associes'][$key] = $associe;
}
I don't really know why I can't access to theses data
there is my entity :
form.php
/**
* #var Form[]
*
* #ORM\ManyToMany(targetEntity="App\Entity\Form")
*/
private $associes;
public function __construct(){
$this->created = new \DateTime("now");
$this->associes = new ArrayCollection();
}
/**
* #return Form[]
*/
public function getAssocies()
{
return $this->associes;
}
Someone have an idea to how can I get theses datas in an array ?
I'm trying to get laravel-scout tntsearch with eloquent's query builder, this has proven difficult so my current approach is to first use tntsearch to get results, pluck ids from the results adn then add a wherIn clause with the plucked ids, to do this I have an additional class QueryFilters to sort and filter in a composable way.
Issue is I'm getting the following error:
Call to undefined method App\Filters\QueryFilters::merge()
Here is my code:
public function search(Request $request, QueryFilters $filters)
{
//Search with tntsearch
$posts = Post::search($request->input('search'))->get();
//Grab ids and prepare to merge with $filters
$postIds = $posts->pluck('id');
$toMerge = collect(['whereIn' => $postIds]);
$filters->merge($toMerge);
//Filter and sort results
$posts = Post::filter($filters)->with(['postcategory','author','favorites'])->paginate(10);
}
How QueryFilters works is iterating throught the request object looking for methods with the same name and returning each time an instance of the query builder.
<?php
namespace App\Filters;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
class QueryFilters
{
protected $request;
protected $builder;
public function __construct(Request $request)
{
$this->request = $request;
}
public function title($term)
{
$lowerCaseTerm = strtolower($term);
return $this->builder->where('title', 'LIKE', "%$lowerCaseTerm%");
}
public function postCategory($term)
{
if($term == 0)
{
return $this->builder->whereHas('postcategory', function ($query) use ($term){
$query->where('id', '>', 0);
});
}
return $this->builder->whereHas('postcategory', function ($query) use ($term){
$query->where('id', $term);
});
}
public function sortBy($term)
{
$sortArray = explode(",", $term);
for($i = 0; $i < count($sortArray); $i++)
{
$sortBy = substr_replace($sortArray[$i], "", -1);
$sortChar = substr($sortArray[$i], -1);
$sortOrder = $sortChar == '+' ? 'ASC' : 'DESC';
$this->builder->orderBy($sortBy, $sortOrder);
}
return $this->builder;
}
public function whereIn($postIds)
{
return $this->builder->whereIn('id', $postIds);
}
public function apply(Builder $builder)
{
$this->builder = $builder;
foreach ($this->filters() as $name => $value)
{
//if method doesn't exists continue out of the loop
if ( ! method_exists($this, $name))
{
continue;
}
//method exists so check if it has a value payload so call the method with arguments
if (strlen($value))
{
$this->$name($value);
}
//it doesn't have a payload so call the method without arguments
else
{
$this->$name();
}
}
return $this->builder;
}
public function filters()
{
//returns associative array of request body key value pairs
return $this->request->all();
}
}
To know more about this class see this medium article:
https://medium.com/#mykeels/writing-clean-composable-eloquent-filters-edd242c82cc8
If I dd $filters I get this:
QueryFilters {#457
#request: Request {#43
#json: null
#convertedFiles: null
#userResolver: Closure($guard = null) {#421
class: "Illuminate\Auth\AuthServiceProvider"
this: AuthServiceProvider {#41 …}
use: {
$app: Application {#2 …}
}
file: "C:\xampp\htdocs\dog-media.es\vendor\laravel\framework\src\Illuminate\Auth\AuthServiceProvider.php"
line: "83 to 85"
}
#routeResolver: Closure() {#423
class: "Illuminate\Routing\Router"
this: Router {#26 …}
use: {
$route: Route {#220 …}
}
file: "C:\xampp\htdocs\dog-media.es\vendor\laravel\framework\src\Illuminate\Routing\Router.php"
line: "650 to 652"
}
+attributes: ParameterBag {#45
#parameters: []
}
+request: ParameterBag {#51
#parameters: array:3 [
"loaderId" => "1111"
"postCategory" => "0"
"sortBy" => "created_at+"
]
}
+query: ParameterBag {#51}
+server: ServerBag {#47
...
And my Filter scope:
<?php
namespace App\Filters;
use Illuminate\Database\Eloquent\Builder;
trait Filterable
{
public function scopeFilter($query, QueryFilters $filters)
{
return $filters->apply($query);
}
}
I have this query
$products = DB::table('product_attributes')
->where('product_attributes.attribute_id', '=', $attri->id)
->joinoin('products', 'products.id', '=',
->get();
and it returns
Collection {#2788 ▼
#items: array:2 [▼
0 => {#2785 ▶}
1 => {#2786 ▶}
]
}
but then I don't have access to my products cover image, so I changed my query to:
$products = DB::table('product_attributes')
->where('product_attributes.attribute_id', '=', $attri->id)
->join('products', 'products.id', '=', 'product_attributes.product_id')
->join('covers', 'covers.imageable_id', '=', 'products.id')
->get();
and it returns:
Collection {#2805 ▼
#items: []
}
empty!
Again I changed my query to:
$products = DB::table('product_attributes')
->where('product_attributes.attribute_id', '=', $attri->id)
->leftJoin('products', 'products.id', '=', 'product_attributes.product_id')
->leftJoin('covers', 'covers.imageable_id', '=', 'products.id')
->get();
and it returns:
Collection {#2807 ▼
#items: array:2 [▼
0 => {#2804 ▶}
1 => {#2805 ▶}
]
}
yet without having access to my covers (same as my first query).
question
How can I have access to my products with all other models relations?
More...
here is some of other relations to my product model
public function covers()
{
return $this->hasMany(Cover::class, 'imageable_id');
}
public function photos()
{
return $this->hasMany(Photo::class, 'imageable_id');
}
public function options(){
return $this->belongsToMany(Option::class, 'product_options', 'product_id', 'option_id');
}
public function attributes(){
return $this->belongsToMany(Attribute::class, 'product_attributes', 'product_id', 'attribute_id');
}
public function categories(){
return $this->belongsToMany(Category::class, 'product_categories', 'product_id', 'category_id');
}
If you have the relationships set-up you could do it in the following way:
$products = Product::with(['covers','attributes'])->whereHas('attributes', function ($query) use ($attri) {
$query->where('product_attributes.attribute_id', $attri->id);
})->get();
This way you get all your products which have an attribute with the given identifier and along with those products you will also retrieve the covers and attributes.
To access a cover or attribute in the first product for example you could do $products->first()->covers
Init only main object
$product = Product::findOrFail($id);
Use relations as object. Not use query-builder.
$product->covers();
$product->photos();
$user = User::where('id', $id)->with(['experiences_user'])->first();
dd($user->experiences_user());
When i execute dd it's not showing the values of relationship have.
relations: array:1 [▼
"experiences_user" => Collection {#196 ▼
#items: []
}
User Model Relationships:
public function experiences_user(){
return $this->hasMany('App\experiences', 'User_id');
}
Experiences Model Relationships:
public function employee(){
return $this->belongsTo('App\User','User_id', 'id');
}
Try lazy loading:
$user = User::where('id', $id)->first()->load('experiences_user');
So I'm basically trying to retrieve all "favourites" for a specific user from the pivot table favourite (yes it seems that I started my project by misspelling the word favorite).
So when viewing u/Admin, I should be able to view all games admin has favorited.
public function index(User $user)
{
$favourites = Auth::user()->favourites;
// dd($favourites);
return view('u.index', compact('favourites'));
}
But when dd($favourite);, I'm returned a empty collection.
Collection {#216 ▼
#items: []
}
in m y Users.php i have the following:
public function getRouteKeyName()
{
return 'name';
}
public function favourites()
{
return $this->belongsToMany(Game::class, 'favourites', 'user_id', 'game_slug')->withTimeStamps();
}
Might it have something to do with that Game.php has it route key set to the slug?
public function getRouteKeyName()
{
return 'slug';
}
Try this:
Create a model called 'Favourite'(make sure you have a user_id column in the favourites table)
put this in your controller -> use App\Favourite;
And try this code:
$user_id = Auth::user()->id;
$favourites = Favourite::where('user_id', $user_id)->get();