October CMS overriding list query - laravel

In backend I have a list of records. And this list displays all records of this type. It is possible to override this query?
In controller I have Eloquent query and i grab some data from database,
and i set this data in $query_data variable. Howe push this data in list view?

unfortunately, I didn't get exactly your point of telling override query, if you mean that set some condition in fetching data from database in Eloquent you have to use where for example in the example below we have users which their gender is male:
$users=User::where('gender','male')->get();
for set more condition you can do like this:
$users=User::where([['gender','male'],['status',1]])->get();
and for showing the variable in your view you can use compact method:
return view('YOUR BLADE FILE NAME',compact('users'));
hope be helpful bro

Related

What is the different between laravel PLUCK and SELECT

I found that laravel 'pluck' return an plain array and 'select' return an object. Can anyone explain it to me have any other different between two this?
thank you.
Pluck is a Laravel Collections method used to extract certain values from the collection. You might often want to extract certain data from the collection i.e Eloquent collection.
While Select is a normal selection of either multi or specific columns. They are
By using Pluck you only ask to return necessary fields, but with get you will pull all columns. Also select does the same & the difference here is between the returning result. Using pluck cause returning the final result as an array with pair of given arguments, but select return an array (or object) which every single child contain one row.
$name = DB::table('users')->where('name', 'John')->pluck('name');
Select
EX : DB::table('users')->select('id', 'name', 'email)
Select is a method sent to the database that Laravel will translate as
SELECT id, name, email FROM users
This will select the data of the columns you asked and nothing else. It allows you to be more efficient with your request by only asking the required data. Take the example above and image that the user is a Facebook user. It has a ton of data on it, plus relations to other tables. If you just want to display the name, email and a link to the user profile, doing this request!
For more info and knowing more about the expected response visit : https://laravel.com/docs/9.x/queries#select-statements
Pluck
EX:
$users = DB::table('users')->where('roles', '=', 'admin')
$emails = $users->pluck('email')
The Pluck method retrieves the values in a collection that you already got from the Database and that is now a Laravel Collection. This allows you to create an array of the plucked data, but will not improve the performance of your request, as in the Example above, the $users would hold all data of all the admin users.
Since it does not improve performance, what good is it then ?
The pluck would be useful for example to separate some datas in different variables depending on where. You might need the users data for some stuffs, but also want to display a quick list of all emails together.
For more info about the pluck method and understand how to create a keyed array from a second column, visit the docs here: https://laravel.com/docs/9.x/collections#method-pluck
Pluck function normally used to pull a single column from the collection or with 2 columns as key, value pairs, which is always be a single dimension array.
Select will return all of the columns you specified for an entity in a 2 dimensional array, like array of selected values in an array.
Note: Pluck function is a collection function which happens after the data is fetched. Select is a query builder function that builds query to perform in the database server.
Actually select is used inside DB queries, which can affect the performance by limiting the pulled columns. However, Pluck is Laravel Collection's method, so you can use pluck after you pull the data from DB.

Laravel 6 check if a json field contains a value in a collection

I am trying to see if a user id is contained in a json field in my laravel collection. In my postgresql database I have a user_id field which contains a list of integers that pertain to my user model and table. I am aware in eloquent I can use the whereJsonContains method but I am not finding an equivalent method for a collection. How can I go about searching this user_id column for a specific user id?
check the manual for the aviable methods list:
https://laravel.com/docs/8.x/collections#available-methods
In your case i guess that is about:
where

what is difference between model->name and model() in laravel?

I want to know the difference between laravel eloquent conisgnment->runsheet->name and $consignment->runsheet()->name
i notice that there is performance difference but why? also I notice that when I try to get relationship property like $consignment->runsheet->name it work fine but $consignment->runsheet()->name doesn't work
The first one
$consignment->runsheet
retrieve a collection (so it's already made a query to DB)
while the second
$consignment->runsheet()
is a query builder (hasn't made a database query) you can chain it like any query builder instance
so if you want to get a property from the second one you can do it like:
$consignment->runsheet()->first()->name;
OR
$consignment->runsheet()->value('name');

How to create a GraphQL query that returns data from multiple tables/models within one field using Laravel Lighthouse

Im trying to learn GraphQL with Laravel & Lighthouse and have a question Im hoping someone can help me with. I have the following five database tables which are also defined in my Laravel models:
users
books
user_books
book_series
book_copies
I'd like to create a GraphQL endpoint that allows me to get back an array of users and the books they own, where I can pull data from multiple tables into one subfield called "books" like so:
query {
users {
name
books {
title
issue_number
condition
user_notes
}
}
}
To accomplish this in SQL is easy using joins like this:
$users = User::all();
foreach ($users as $user) {
$user['books'] = DB::select('SELECT
book_series.title,
book.issue_number
book_copies.condition,
user_books.notes as user_notes
FROM user_books
JOIN book_copies ON user_books.book_copy_id = book_copies.id
JOIN books ON book_copies.book_id = books.id
JOIN book_series ON books.series_id = book_series.id
WHERE user_books.user_id = ?',[$user['id']])->get();
}
How would I model this in my GraphQL schema file when the object type for "books" is a mashup of properties from four other object types (Book, UserBook, BookCopy, and BookSeries)?
Edit: I was able to get all the data I need by doing a query that looks like this:
users {
name
userBooks {
user_notes
bookCopy {
condition
book {
issue_number
series {
title
}
}
}
}
}
However, as you can see, the data is separated into multiple child objects and is not as ideal as getting it all in one flat "books" object. If anyone knows how I might accomplish getting all the data back in one flat object, Id love to know.
I also noticed that the field names for the relationships need to match up exactly with my controller method names within each model, which are camelCase as per Laravel naming conventions. Except for my other fields are matching the database column names which are lower_underscore. This is a slight nitpick.
Ok, after you edited your question, I will write the answer here, to answer your new questions.
However, as you can see, the data is separated into multiple child objects and is not as ideal as getting it all in one flat "books" object. If anyone knows how I might accomplish getting all the data back in one flat object, Id love to know.
The thing is, that this kind of fetching data is a central idea of GraphQL. You have some types, and these types may have some relations to each other. So you are able to fetch any relations of object, in any depth, even circular.
Lighthouse gives you out of the box support to eloquent relations with batch loading, avoiding the N+1 performance problem.
You also have to keep in mind - every field (literally, EVERY field) in your GraphQL definition is resolved on server. So there is a resolve function for each of the fields. So you are free to write your own resolver for particular fields.
You actually can define a type in your GraphQL, that fits your initial expectation. Then you can define a root Query field e.g. fetchUsers, and create you custom field resolver. You can read in the docs, how it works and how to implement this: https://lighthouse-php.com/5.2/the-basics/fields.html#hello-world
In this field resolver you are able to make your own data fetching, even without using any Laravel/Eloquent API. One thing you have to take care of - return a correct data type with the same structure as your return type in GraphQL for this field.
So to sum up - you have the option to do this. But in my opinion, you have to write more own code, cover it with tests on you own, which turns out in more work for you. I think it is simpler to use build-in directives, like #find, #paginate, #all in combination with relations-directives, which all covered with tests, and don't care about implementation.
I also noticed that the field names for the relationships need to match up exactly with my controller method names within each model, which are camelCase as per Laravel naming conventions.
You probably means methods within Model class, not controller.
Lighthouse provides a #rename directive, which you can use to define different name in GraphQL for your attributes. For the relation directives you can pass an relation parameter, which will be used to fetch the data. so for your example you can use something like this:
type User {
#...
user_books: [Book!]! #hasMany(relation: "userBooks")
}
But in our project we decided to use snak_case also for relations, to keep GraphQL clean with consistent naming convention and less effort

How to fetch specified attributes from $this->belongsTo() in Laravel Eloquent?

I want to fetch some particular field from table rather than complete attributes in $this->belongsTo(); I can't use select('field_name') or pluck('field_name') or DB::raw(count(),avg()) etc with belongsTo,hasTo() .....
How i solve this problem?
I can't use
$this->belongsTo()->select('fiel_name')
or
$this->belongsTo()->pluck('fiel_name')
Please check the reference : How to join three table by laravel eloquent model
In the above reference, They fetched all attributes in blengsTo(), But in my case i have to fetch only particular attributes.
You have to use it like this
$this->belongsTo('Model')->select(array('field_name'));
where Model can be for example User etc.

Resources