Laravel Tutorials
- What is laravel
- Laravel Installation
- Directory Structure
- htaccess
- Remove public from url
- Artisan Command
- Laravel Configuration
- Routing Configuration
- Namespaces
- Request
- Response
- Controller
- Model
- User Authentication
- Multi User Authentication
- Database Seeding
- Database
- Database Query
- ORM
- One-to-One Relationship
- One-to-Many Relationship
- Many to Many Eloquent Relationship
- Has One Through
- Has Many Through
- Querying Relations
- Middleware
- Laravel Views
- Blade Views
- Print data on view page
- Get Site URL
- Get URL Segment
- Get images from Storage folder
- Clear cache
- Form Class not found
- Flash Message in laravel
- Redirections
- path
- CRUD Projerct
- CRUD in Laravel
- CRUD progran
- Laravel Validation
- Jquery Validation
- Cookie
- Session
- Email Send in laravel
- File uploading
- CSRF Protection
- Helper in Laravel
- Helper Functions
- Guzzle Http Client
- Paypal Payment Gatway Integration
- Cron Job in laravel
- Flash message
- path
- Errors Handling
- Date Format
- Date Format Validation
- Display Image on View Page
- Update User Status using toggle button
- Delete Multiple Records using Checkbox in Laravel?
- Confirmation Before Delete Record
- Delete image from storage
- Remove/Trim Empty & Whitespace From Input Requests
- Block IP Addresses from Accessing Website
- How to Disable New User Registration in Laravel
- Redirect HTTP To HTTPS Using Laravel Middleware
- CKEditor
- slug generate unique
- Prevent Browser's Back Button After Logout
- Datatable dunamically
- encrypt & Decript
- Download File
- Rest API
- Shopping Cart
- Shopping Cart Example
- Dynamic Category-Subcategory Menu
- Ajax Search
- Interview Question
- laravel Tutorilal link
- laravel Tutorilal
Important Links
How to use One to Many Eloquent Relationship in laravel?
One To Many relationship also known as hasMany relationship links one row in the database table to many rows in other database tables.
when one table associated with multiple tables is called one-to-many relationship.
In Laravel Eloquent, one model can owns multiple models which is one to many link. For example, in a ecommerce application scenario a Brand model can have many Product model and a Product model belongs to a Brand model.
posts table migration
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string("name");
$table->timestamps();
});
comments table migration
File name : index.php
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->string("comment");
$table->timestamps();
$table->foreign('post_id')->references('id')->on('posts')
->onDelete('cascade');
});
Post Model:
File name : Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany(Comment::class);
}
}
comment model
File name : comment.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo(Post::class);
}
}
Retrieve Records:
File name : index.php
$post = Post::find(1);
$comments = $post->comments;
dd($comments);
$comment = Comment::find(1);
$post = $comment->post;
dd($post);
Create Records:
File name : index.php
$post = Post::find(1);
$comment = new Comment;
$comment->comment = "Hi ItSolutionStuff.com";
$post = $post->comments()->save($comment);
$post = Post::find(1);
$comment1 = new Comment;
$comment1->comment = "Hi itechxpert comment 1";
$comment2 = new Comment;
$comment2->comment = "Hi itechxpert Comment 2";
$post = $post->comments()->saveMany([$comment1, $comment2]);
$comment = Comment::find(1);
$post = Post::find(2);
$comment->post()->associate($post)->save();
Example
File name : index.php
Example :-
Create Company Model And Migrations
File name : index.php
php artisan make:model Company -m
File name : TIMESTAMP_create_companies_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCompaniesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('company_name');
// You can add more fields about company if require
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('companies');
}
}
Company Model
File name : Company.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $fillable = [
'company_name'
];
}
Create Car Model And Migrations
File name : index.php
php artisan make:model Car -m
File name : TIMESTAMP_create_cars_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCarsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('cars', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('model');
$table->float('price', 10, 2);
$table->unsignedBigInteger('company_id');
// You can add more fields about car if require
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('cars');
}
}
Car Model
File name : Car.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Car extends Model
{
protected $fillable = [
'model', 'price', 'company_id'
];
}
File name : index.php
Define One To Many Relationship
define one to many relationship between company and car model.
File name : index.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
// -- OTHER CODE
/**
* Get the cars for the blog post.
*/
public function cars()
{
return $this->hasMany('App\Car');
}
}
Note :- The hasMany method define relationship between company and car eloquent model. Remember, Eloquent will automatically determine the proper foreign key column on the Car model. By convention, Eloquent will take the “snake case” name of the owning model and suffix it with _id. So, for this example, Eloquent will assume the foreign key on the Car model is company_id
if you are not following above convention method to define foreign key relationship between two models then you need to define foreign_key and local_key in hasMany method like this:
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
In this example, we have company_id (Inside cars table) is foreign key and id (Inside companies table) is local key.
Retrieve Relationship Data
File name : index.php
$cars = Company::find(1)->cars; // For single company
$cars = Company::with('cars')->get(); // For multiple companies
show data on view blade
File name : view.php
public function show_car(Request $request)
{
$cars = Company::find(1)->cars; // For single company
//$cars = Company::with('cars')->get(); // For multiple companies
//print_r($cars);
//exit;
//$company = Car::find(1)->company; // For single data
//$companies = Car::with('company')->get(); // For multiple data
return view('admin.carlist',compact('cars'));
}
File name : carlist.php
<tbody>
<?php $i = 1; ?>
@foreach($cars as $row)
<tr>
<th>{{$i++}}</th>
<td>{{$row->company->company_name}}</td>
<td>{{$row->model}}</td>
<td>{{$row->price}}</td>
<td>
<a href="javascript:void(0);" class="btn btn-default waves-effect waves-float waves-green edit-aboutus" id='del_{{$row->id}}' data-id='{{$row->id}}'><i class="zmdi zmdi-edit"></i></a>
<button class='delaboutus btn btn-danger' title="Delete" id='del_{{$row->id}}' data-id='{{$row->id}}' > <i class="zmdi zmdi-delete"></i></button>
</td>
</tr>
@endforeach
</tbody>
Define Inverse Relationship
File name : index.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Car extends Model
{
// -- OTHER CODE
/**
* Get the company that owns the cars.
*/
public function company()
{
return $this->belongsTo('App\Company');
}
}
The belongsTo method is used to define inverse relationship between car and company eloquent model. Again remember that eloquent will find out foreign_key and local_key based on model name if you have followed conventional method. Somehow, if you override it then you need to pass all three arguments into belongsTo method like this.
return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
In this example, foreign_key is company_id (In cars table) and local_key is id (In companies table). Make sure that local_key if primary_key.
Retrieve Inverse Relationship Data
File name : index.php
$company = Car::find(id)->company; // For single data
$companies = Car::with('company')->get(); // For multiple data
File name : index.php