Category Archives: Laravel

Laravel Tutorials

Laravel Eloquent Relationships Example

In this Laravel Eloquent Relationships example tutorial, I’ll show you how to create and use eloquent relationships in laravel database model. In this article we will learn to implement and use different types of eloquent model relation available in laravel. We will also learn to perform create, insert and to delete operations in different type of relationships.

Type of Laravel Eloquent Relationships

In laravel, there are following types of eloquent relationships available:

Laravel One to One Relationship Example

The one to one relationship is a very common relationship in laravel model. In this example we will learn to implement and use one to one relationship in laravel. We will also show you how to  insert, retrieve, update, and delete data with the eloquent model from the database table in laravel.

Laravel Eloquent One to One Relationship Example

Let suppose we have two tables posts and contents in our example tutorial. In laravel we can create both tables using migration as following:

Post table migration:

Contents table migration:

In this example, the Post model is closely associated with a Content model in one to one relationship. In one to one relationship we will create a post_content() method within the Post model and there is hasOne() method to relate it with Content model as following.

The Eloquent model adds a foreign key based on the model name and should have a matching id value in it. In this relationship the post_id is the foreign_key for Content model,

Inverse of One to One Relationship Example

For now we can have the access to the content from the post model. Now we create an inverse relationship in the content model. For this we will use the belongsTo method for getting the post data from the content model as following.

We can now access the post content using the relation method as following:

Laravel One to Many Relationship Example

In this step by step tutorial I’ll guide you through to create many to many relationship and learn how to use this relationship. In this example we will use one to many relationship, and perform crud (create, read, update, delete) operation with the eloquent model from the database table in laravel.

Laravel Eloquent One to Many Relationship Example

Let suppose we have  tables name posts and authors. Using laravel migration, you can create both tables with the following fields:

Author table migration:

Post table migration:

Define One To Many Relationship

Now we will define One To Many Relationship for the model we have created. In One to many relationships means a relationship where one single model can owns the number of the other model. As per the example model we created, a single author can have written many post articles. Let’s take an example of one to many relationships.

Now, we can access the collection of post articles by using the post() method as.

Defining Inverse One To Many Relationship in Laravel

As of now we can access all the post articles of an author, now suppose if we want to allow a post model to access its Author model or access author details by using the post model. The inverse relationship of both One to One and One to Many works the same way. The inverse of the one to many relationship can be defined using the belongsTo method. Thus we can define in example mode as following:

Now we can get the author details by using posts in one to many relationship as following:

Retrieving Data In One to many relationship

In one to many relationship you can retrieve data from model as following:

You can get all posts of a particular author:

Similarly, you can retrieve the inverse related model.

Laravel Many to Many Relationship Example

In laravel using belongsToMany() method, you can define many to many relationship in laravel eloquent models. Then you can insert, update and delete data from table using many to many relationship in laravel.

Laravel Eloquent Many to Many Relationship Example

In this example we will demonstrate the implementation of Many to Many Relationship using two tables posts and tags. In this relationship each of the post can have many tags and each of the tag can be associated with many posts.

Now, lets understand how to define many to many relationships, Using belongsToMany() method:

Now, you  can access the tags in the post model as follow:

The inverse of Many to Many Relationship Example

In Laravel, the inverse relationship of a many to many relationships can be defined using belongsToMany method on the reverse model.

Now you can access the post in the tag model as follow:

Laravel Eloquent HasMany Through Relationship Example

In this Laravel Has Many Through Eloquent Relationship tutorial we will implement an example for the Laravel Has Many Through Eloquent Relationship. We will generate migration files of “users”, “posts” and “countries” table and then add a foreign key with users and posts table as following:

In users migration file:

In posts migration file:

In countries migration file:

In laravel, the “has-many-through” relationship provides a shortcut for accessing distant relations via an intermediate model relation. For example, a Country model might have many Post models through an intermediate User model. In this example,  we can easily get all blog posts of a given country. I’ll show you how to define HasMany Through relationship:

To fetch data using this relationship as follow:

Laravel One to One Relationship Example

In this Laravel one to one relationship example tutorial, I’ll show you to implement one to one relationships In laravel eloquent model. You will also learn how to create and use one to many relationship in laravel.

Laravel One to One Relationship Example

The one to one relationship is a very common relationship in laravel model. In this example we will learn to implement and use one to one relationship in laravel. We will also show you how to  insert, retrieve, update, and delete data with the eloquent model from the database table in laravel.

Laravel Eloquent One to One Relationship Example

Let suppose we have two tables posts and contents in our example tutorial. In laravel we can create both tables using migration as following:

Post table migration:

Contents table migration:

In this example, the Post model is closely associated with a Content model in one to one relationship. In one to one relationship we will create a post_content() method within the Post model and there is hasOne() method to relate it with Content model as following.

The Eloquent model adds a foreign key based on the model name and should have a matching id value in it. In this relationship the post_id is the foreign_key for Content model,

Inverse of One to One Relationship Example

For now we can have the access to the content from the post model. Now we create an inverse relationship in the content model. For this we will use the belongsTo method for getting the post data from the content model as following.

We can now access the post content using the relation method as following:

Laravel Insert record in one to one relationship

You can insert record in post and content table using one to one relationship as following:

Now, if you want to retrieve data from both post and content table, you can use one to one relationship as following:

Laravel Delete record in One to One relationship

Now, to delete record from both tables posts and contents in one to one relationship, you can do it as following:

Laravel One to Many Relationship Example

In this Laravel one to many relationship example tutorial I’ll show you how to implement one to many relationship in laravel eloquent model. You will also learn how to use create, and retrieve records from database tables using one to many relationship.

Laravel One to Many Relationship Example

In this step by step tutorial I’ll guide you through to create many to many relationship and learn how to use this relationship. In this example we will use one to many relationship, and perform crud (create, read, update, delete) operation with the eloquent model from the database table in laravel.

Laravel Eloquent One to Many Relationship Example

Let suppose we have  tables name posts and authors. Using laravel migration, you can create both tables with the following fields:

Author table migration:

Post table migration:

Define One To Many Relationship

Now we will define One To Many Relationship for the model we have created. In One to many relationships means a relationship where one single model can owns the number of the other model. As per the example model we created, a single author can have written many post articles. Let’s take an example of one to many relationships.

Now, we can access the collection of post articles by using the post() method as.

Defining Inverse One To Many Relationship in Laravel

As of now we can access all the post articles of an author, now suppose if we want to allow a post model to access its Author model or access author details by using the post model. The inverse relationship of both One to One and One to Many works the same way. The inverse of the one to many relationship can be defined using the belongsTo method. Thus we can define in example mode as following:

Now we can get the author details by using posts in one to many relationship as following:

Retrieving Data In One to many relationship

In one to many relationship you can retrieve data from model as following:

You can get all posts of a particular author:

Similarly, you can retrieve the inverse related model.

Inserting Data In One to Many relationship

To Insert data in one to many relationship between two models, we can first create a child object and then save it using the parent object as following:

Filtering Data In one to many relationship

If you want to filter the related records and want them to sort when retrieving. You can chain the methods on your retrieving query.

Deleting Data In One to Many relationship

Deleting of records in one to many relationship is performed same as we have created them. To delete all posts for a particular author use below code example.

Laravel Many to Many Relationship Example

In this Laravel many to many relationship example tutorial.I’ll show you how to implement and use many to many relationship along with the inverse of the many to many relationship.

Laravel Many to Many Relationship Example

In laravel using belongsToMany() method, you can define many to many relationship in laravel eloquent models. Then you can insert, update and delete data from table using many to many relationship in laravel.

Laravel Eloquent Many to Many Relationship Example

In this example we will demonstrate the implementation of Many to Many Relationship using two tables posts and tags. In this relationship each of the post can have many tags and each of the tag can be associated with many posts.

Now, lets understand how to define many to many relationships, Using belongsToMany() method:

Now, you  can access the tags in the post model as follow:

The inverse of Many to Many Relationship Example

In Laravel, the inverse relationship of a many to many relationships can be defined using belongsToMany method on the reverse model.

Now you can access the post in the tag model as follow:

Laravel Has Many Through Eloquent Relationship Example

In this Laravel HasManyThrough relationship example tutorial, I’ll show you how to create hasmany through relationship in eloquent models. In this tutorial you will also learn to implement and use Laravel Has Many Through Eloquent Relationship.

Laravel Eloquent HasMany Through Relationship Example

In this Laravel Has Many Through Eloquent Relationship tutorial we will implement an example for the Laravel Has Many Through Eloquent Relationship. We will generate migration files of “users”, “posts” and “countries” table and then add a foreign key with users and posts table as following:

In users migration file:

In posts migration file:

In countries migration file:

In laravel, the “has-many-through” relationship provides a shortcut for accessing distant relations via an intermediate model relation. For example, a Country model might have many Post models through an intermediate User model. In this example,  we can easily get all blog posts of a given country. I’ll show you how to define HasMany Through relationship:

To fetch data using this relationship as follow:

Laravel One to Many Polymorphic Relationship Example

In this Laravel One to Many Polymorphic Relationship Example tutorial, I’ll show you how to implement laravel one to many polymorphic relationship and you will also learn how to use create, and retrieve records from database tables using this relationship.

Laravel One to Many Polymorphic Relationship Example

Developing any blogging portal application and you would have many tables like posts, videos and comments. You would need to add comments for posts and videos. In this scenario you can use One to Many Polymorphic Model Relationship in laravel. Because your comments model belongs to more than one model.

In Laravel  “morphMany()” and “morphTo()”  eloquent method allows you to create One to Many Polymorphic Relationship in your laravel eloquent models.

Create Migration File

In this example we will create posts, videos and comments migration files with following files:

posts migration file:

videos migration file:

comments migration file:

Create one to many polymorphic relationships in model

Now, we can create one to many polymorphic relationships as following:

Post Model:

Video Model:

Comment Model:

Retrieve, create a record using polymorphic relationship

Now you will learn how to retrieve and create a record from posts, videos and comments table using one to many polymorphic relationship:

Retrieve Records:

Create Records:

Laravel Many to Many Polymorphic Relationship Example

In this Laravel Many to Many Polymorphic Relationship Example tutorial, I’ll show you how to implement laravel many to many polymorphic relationship in laravel eloquent model. You will also learn how to use create, and retrieve records from database tables using Many to Many Polymorphic Relationship.

Laravel Many to Many Polymorphic Relationship Example

In laravel, “morphToMany()” and “morphedByMany()” eloquent method allows you to create Many to Many Polymorphic Relationship in your laravel eloquent models.

In this step by step tutorial I’ll guide you through to create many to many polymorphic relationship and learn how to use this relationship:

Create Migration File

In this example we will create posts, videos, tags and taggables migration files as following:

database/migrations/posts

database/migrations/videos 

database/migrations/tags 

database/migrations/taggables 

Create many to many polymorphic relationships in model

Next, create many to many polymorphic relationships as follow:

app/Post.php

app/Video.php

app/Tag.php

Insert and retrieve a record using many to many polymorphic relationship

Now I will show you how to insert and retrieve a record from posts, videos tags, and taggables table in many to many polymorphic relationship:

Retrieve Records From table

Find post tags as follow:

Find video tags as follow:

and you can find post and video of a specific tag like

Insert Records in Table

Now we can Insert tag for the post into DB table as following:

Insert tag for the following video into DB table as follow:

Insert Multiple Tags for Post:

Using sync or attach to insert multiple tag as follow:

Or use sync

Laravel whereExists and whereNotExists Query Example

In this Laravel whereExists and whereNotExists Query Example tutorial, I will show how to use whereExists and whereNotExists methods with eloquent in laravel query builder and laravel model.

Laravel whereExists and whereNotExists Query Example

Suppose you are developing a job portal in laravel. In this portal an employer can post a job and hire employees as per the require positions. When an employer posts a job and they wants to hire only manager or web developer. In this case we have to face problem because you have registered users of different designations.

Suppose you have the following tables into your job application:

positions table

id | title | timestamps

users table

id | name | email | timestamps

users_position table (a pivot table for user and position)

id | user_id | position_id | description | timestamps

jobs table

id | position_id | name | description | timestamps

Laravel whereExists Using Eloquent Model Example

In this example we will demonstrate the use of whereExists() method in laravel. As per the above database tables If you are an employer and you are looking to hire for some specific position employee. Then you have posted a new job and wants to hire an employees. So you will be notified by sending an email for a new job opportunity for specific designation users.

If you have a large amount of registered users in your job application, now you don’t want to get them all and to make sure that only those job applicants who are Banker will receive the email.

Here you can use laravel whereExist query as following:

This above query will fetch all users from the users table, and used whereExist clause and use a closure argument to apply condition.

Laravel whereNotExists Using Eloquent Model Example

In this example I’ll demonstrate the use of whereNotExists() method using the above tables as following:

As per the above database schema suppose you want to post a new job and want to hire employees. Now you want to send emails of this new job opening to specific designation users and want to skip other designation users.

Now the problem with this is you have a large amount of users registered in your job portal, now you don’t them all to make sure that only those job applicants who are Not Banker, Designer, etc will receive the email.

Now, here you can use laravel whereNotExist query as following:

This above query will fetch all users from the users table, and used whereNotExist clause and use a closure argument.

Laravel 7 Datatables with Relationship Example

In this Laravel dataTables with relationship example tutorial I’ll show you how to display and filter column in yajra dataTables with relationship.

Laravel 7 Datatables with Relationship Example

Let suppose you have two database tables first is posts and the other one is users and you have relationship in each table. Now you want to display and filter posts title and who write these posts (author name). This would require you to use laravel yajra dataTables columns with a relationship.

In this tutorial I’ll  demonstrates you to how to use a filter on dataTables columns with relationships.

  • Download Laravel Fresh App
  • Setup Database Configuration
  • Install Yajra DataTable
  • Create Migration and Modal
  • Create route
  • Generate Controller by Command
  • Create Blade File
  • Run Development Server

Install Laravel 7/6

First of all we need to create a fresh laravel project, download and install Laravel 7/6 using the below command

Configure Database In .env file

Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.

.env

Run Migration

Now, we need to create migration of tables using following command:

Install Yajra Datatable Package

In this step, we will install Yajra Datatables Package via the composer dependency manager. Use the following command to install Yajra Datatables Package.

After Installing Yajra Datatables package, we need to add service provider and alias in config/app.php file as following.

config/app.php

After set providers and aliases then publish vendor run by the following command.

Create Migration and Modal

Now let’s create post table migration and create Post Modal using following artisan command:

This will create migration, open migration file and put the following code in it:

database/migrations/YYY_MM_DD_070104_create_posts_table.php

Now run the following command

After you have to put bellow code in your Post model file for create posts table.Now you need to open app/Post.php model and create relationship in this model as following:

app/Post.php

Create route

Now, open your “routes/web.php” file and add the following route in it:

routes/web.php

Generate Controller by Command

Now, create a new controller PostController using following artisan command:

Once the above command executed, it will create a controller file PostController.php in app/Http/Controllers/directory. Open the PostController.php file and put the following code in it.

app/Http/Controllers/PostController.php

Create Blade File

In this step, we will create view/blade file. Lets create a blade file “users.blade.php” in “resources/views/” directory and put the following code in it respectively.

resources/views/users.blade.php

Start Development Server

Let’s start the development server using following artisan command:

Now, visit the following link in browser to see the output:

Laravel Eloquent whereTime Query Example

In this Laravel Eloquent whereTime Query Example tutorial I’ll show you how to use eloquent method with laravel query builder and model.

Laravel Eloquent whereTime Query Example

While working with laravel database you want query records of specific time only. In this case  laravel whereTime() method is very helpful to query records with specific time. In this tutorial we will demonstrate the various example of laravel whereTime method:

Laravel whereTime method with query builder

In this example we will be using whereTime method with laravel query builder as following:

Laravel whereTime method with eloquent model

In this example we will be using laravel whereTime method with eloquent model as following:

you can also write this whereTime query without operator as follow:

Laravel Chunk Eloquent Method Example

In this laravel eloquent chunk method example tutorial, I’ll show you how to use laravel chunk method with large records in laravel. You will also learn How to insert big data on the laravel by using chunk.

Laravel Eloquent Chunk() Method

In Laravel, eloquent chunk method is used to break the large amount of data set into smaller group of sub data set also called as chunks.

Suppose, you are working with a large amount of dataset in application database. This makes working with large amount of dataset in one go more difficult that time laravel chunk method will help you break a larger group of data set into a smaller groups of data set (chunks).

In this method we will demonstrate the use of laravel eloquent chunk method with different examples:

Use laravel chunk with Eloquent Model

View:

This method work with all types of laravel collections, see the following example:

Send Email with Laravel chunk

Let suppose you have big list of users to send emails and you have to send an email to all users. Sometimes it becomes problem that you cannot send email on 10000 emails in one go. In this case  you can use Chunk method of Laravel to break large amount of user list into small sub set of users so you can easily send mail to everyone. See the following example:

Insert big data on the laravel

If you want to insert large amount of data on laravel databse then you can do this with the help of laravel chunk as follow:

Make chunk of your choice

Then use foreach loop to insert by 100 each time

Laravel Group by Example Tutorial

In this Laravel group by example tutorial I’ll show you how to use group by in laravel qloquent query. In this tutorial you will learn how to use laravel group with raw, laravel group by multiple, laravel group by date, laravel group by sum, laravel group by month and laravel collection group by count.

Laravel Group by Example Tutorial

In this tutorial I will guide you through different use case of the laravel group by eloquent query.

  • 1: Laravel GroupBy with Collection Example
  • 2: Laravel Collection Group By Preserve Key
  • 3: Laravel Collection Group By with Multiple Columns
  • 4: Laravel Collection Group By with Date
  • 5: Laravel Collection Group By with Count
  • 6: Laravel Collection Group By with Sum

Laravel GroupBy with Collection Example

In this example we will use laravel groupBy with collection.

Result:

Laravel Collection Group By Preserve Key

In this example use same example as above but we will pass preserve key as true.

Result:

Laravel Collection Group By with Multiple Columns

In this example we will use laravel groupBy with multiple columns.

Result:

Laravel Collection Group By with Date

In this example we will use laravel groupBy with date column.

Result:

Laravel Collection Group By with Count

In this example we will use laravel groupBy with count method.

Result:

Laravel Collection Group By with Sum

In this example we will use laravel groupBy with sum method.

Result: