
OrderBy on Eloquent relationships method in Laravel
You can directly call the orderBy() method on eloquent relationships to get the data from related tables in specific order.
Answers 1
-
Use orderBy method with ASC on eloquent relationship in Laravel to display content in alphabetical ascending order (From A to Z)
//Define relationship method in user model - app\Models\User.php public function postsByTitle(){ return $this->hasMany('App\Models\Post')->orderBy('title', 'ASC'); }
0Calling the relationship method
$data = App\Models\User::find(1)->postsByTitle()->get();
Additional Note
You can display data using foreach loop.
foreach($data as $val){ echo $val->title. "<br/>"; }
You can specify orderBy() directly on your Eloquent relationships. It will return the data in a specific order while calling the relationship method using with() in Laravel. In our case, we get the data in alphabetical ascending order (From A to Z).
Random Code Snippet Queries: Laravel
- Laravel create multiple records in Pivot table
- How to pass two variables in HREF in laravel
- Get count of filter data, while return a small set of records
- How to create project_user pivot table in laravel
- How to get specific columns using Laravel eloquent methods
- Argument 1 passed to Illuminate\Database\Query\Builder::cleanBindings() must be of the type array, null given
- FirstOrCreate() Not Inserting Model
- How to send ID to another page in Laravel
- Laravel hasmany select not working
- Database transactions in laravel
- Laravel order by date not working
- How to make Copy or Duplicate table row in laravel
- Create records using relationship in laravel
- Create project table with model and migration
- In order to use the Auth::routes() method, please install the laravel/ui package
- Call to undefined relationship [user] on model [App\Models\Post]
- Extract only time from datetime in laravel
- How to restore multiple records after soft-deletes in Laravel
- Laravel route parameter
- Use withCount() to get total number of records with relationship
- Store logged in user details in session and display in view in laravel
- Trying to access array offset on value of type null error in laravel
- How to add active class to menu item in laravel
- Get comma separated email from input array
- Argument 1 passed to App\Http\Controllers\Auth\LoginController::authenticated() must be an instance of App\Http\Controllers\Auth\Request