
Rename Pivot Table in Laravel
Sometimes you have to rename the pivot with a specific name while getting data from the pivot table. Usually you have to use the pivot name like $podcast->pivot->created_at while getting the data from pivot table but you can rename the pivot with a specific name which you want to use in Laravel.
-
Use specific name instead of pivot while getting data from pivot table in Laravel
--PATH app\Models\User.phppublic function podcasts() { return $this->belongsToMany('App\Models\Podcast') ->as('subscription') ->withTimestamps(); } //routes\web.php Route::get('/get-podcasts-subscription', function(){ $data = App\Models\User::with('podcasts')->find(1); foreach ($data->podcasts as $podcast) { // instead of $podcast->pivot->created_at ... echo $podcast->subscription->created_at; } });
0You have to follow the laravel naming convention while defining the models name and tables name. It will help you to rename the pivot with subscription while fetching the data from pivot table. Which is more understandable as compared to using pivot.
Additional Notes :
1. Create tables with name users, podcasts and pivot podcast_user table with column user_id, podcast_id, created_at and updated_at column.
2. Create models with name User, Podcast, PodcastUser in app/Models directory.
Random Code Snippet Queries: Laravel
- How to use more than one query scope in Laravel
- How to Get records between two dates in Laravel
- Ajax POST request in laravel
- How to create and run user seeder in laravel
- Pagination in laravel
- How to use or operator in laravel
- How to pass link from controller to view in laravel on ajax call
- Property [user] does not exist on this collection instance
- Display data in table using foreach in Laravel
- Update record after find method in lavavel
- Extra Filter Query on Relationships in Laravel
- FirstOrCreate() Not Inserting Model
- Method Illuminate\Database\Eloquent\Collection::appends does not exist
- Display success message in laravel
- Permission denied error while creating storage link in Laravel
- Laravel create default admin user
- Get Array of IDs from Eloquent Collection
- Order by multiple columns in Laravel
- How to pass external link in laravel blade to anchor tag
- Get only 10 records from table in laravel
- Get current month records in laravel 7/8
- Create model with migration and seeder
- Page loader in laravel
- Laravel pagination links with query string
- How to return error message from controller to view in laravel