PHP & Web Development Blogs

Search Results For: relationship
Showing 1 to 3 of 3 blog articles.
13914 views · 5 years ago
Laravel Eloquent Relationship Part 1

Laravel introduces eloquent relationships from laravel 5.0 onwards. We all know, while we creating an application we all have foreign keys. Each table will be connected to some other. Eloquent make easy to connect each tables easily. Here we will One to one, one to many and many to many relationships. Here we will see three types of relationships,
   
. One to one relationships
    . One to many relationships
    . Many to many relationships

Why Eloquent Relationships

Here we have 2 tables, students and marks, so for join each table,

$student = student::join(‘marks’,’marks.student_id,’=’,students.id’)->where(‘students.id’,’1’)->get();

dd($student);



the above query is to long, so when we connect more tables its too tough we will be having a big query and complicated.



Model Query using Relationships


$student_marks = student::find(1);

dd($student_marks->mark1);



The above example is a simple example of eloquent relationships. We can reduce the first query into a simple one.





ONE TO ONE RELATIOSHIPS

Here we are creating 2 tables:
* Users
* Phones

Now we can see one to one relationships using hasone() and belongsto().

We need to create table using migrations



Create migrations


users table will be created by using


Schema::create('users', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('email')->unique();

$table->string('password');

$table->rememberToken();

$table->timestamps();

});


Phones table will be created by


Schema::create('phones', function (Blueprint $table) {

$table->increments('id');

$table->integer('user_id')->unsigned();

$table->string('phone');

$table->timestamps();

$table->foreign('user_id')->references('id')->on('users')

->onDelete('cascade');

});



After that we need to create model for each tables, as we all know if the table name is laravel table name will be ending with ‘s’ and model name will be without ‘s’ of the same table name.



User model



<?php

namespace App;

use Illuminate\Notifications\Notifiable;

use Illuminate\Foundation\Auth\User as Authenticatable;



class User extends Authenticatable

{

use Notifiable;





protected $fillable = [

'name', 'email', 'password',

];





protected $hidden = [

'password', 'remember_token',

];





public function phone()

{

return $this->hasOne('App\Phone');

}

}



Phone Model



<?php

namespace App;

use Illuminate\Database\Eloquent\Model;



class Phone extends Model

{



public function user()

{

return $this->belongsTo('App\User');

}

}



For Creating records



$user = User::find(1);

$phone = new Phone;

$phone->phone = '9080054945';

$user->phone()->save($phone);



$phone = Phone::find(1);

$user = User::find(10);

$phone->user()->associate($user)->save();



Now we can get our records by


$phone = User::find(1)->phone;

dd($phone);



$user = Phone::find(1)->user;

dd($user);





ONE TO MANY RELATIONSHIPS

Here we will use hasMany() and belongsTo() for relationships

Now we are creating two tables, posts and comments, we will be having a foreign key towards posts table.


Migrations for posts and comments table


Schema::create('posts', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});



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');

});



Now we will create Post Model and Comment Model



Post Model



<?php

namespace App;

use Illuminate\Database\Eloquent\Model;



class Post extends Model

{



public function comments()

{

return $this->hasMany(Comment::class);

}

}



Comment Model



<?php

namespace App;

use Illuminate\Database\Eloquent\Model;



class Comment extends Model

{



public function post()

{

return $this->belongsTo(Post::class);

}

}



Now we can create records


$post = Post::find(1);

$comment = new Comment;

$comment->comment = "Hi Harikrishnan";

$post = $post->comments()->save($comment);

$post = Post::find(1);



$comment1 = new Comment;

$comment1->comment = "How are You?";

$comment2 = new Comment;

$comment2->comment = "Where are you?";

$post = $post->comments()->saveMany([$comment1, $comment2]);



$comment = Comment::find(1);

$post = Post::find(2);

$comment->post()->associate($post)->save();



Now we can get records


$post = Post::find(1);

$comments = $post->comments;

dd($comments);



$comment = Comment::find(1);

$post = $comment->post;

dd($post);



MANY TO MANY RELATIONSHIPS

Many to many is little bit different and complicated than the above two.



In this example, I will create users, roles, and role, users_tables, here each table will be connected each other using the foreign keys.



Using belongsToMany() we will use see a demo of Many to many relationship



Create Migrations



Schema::create('users', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('email')->unique();

$table->string('password');

$table->rememberToken();

$table->timestamps();

});



Schema::create('roles', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->timestamps();

});



Schema::create('role_user', function (Blueprint $table) {

$table->integer('user_id')->unsigned();

$table->integer('role_id')->unsigned();

$table->foreign('user_id')->references('id')->on('users')

->onDelete('cascade');

$table->foreign('role_id')->references('id')->on('roles')

->onDelete('cascade');

});



Create Models



User Model


<?php

namespace App;

use Illuminate\Notifications\Notifiable;

use Illuminate\Foundation\Auth\User as Authenticatable;



class User extends Authenticatable

{

use Notifiable;





protected $fillable = [

'name', 'email', 'password',

];





protected $hidden = [

'password', 'remember_token',

];





public function roles()

{

return $this->belongsToMany(Role::class, 'role_user');

}

}


Role Model


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;



class Role extends Model

{



public function users()

{

return $this->belongsToMany(User::class, 'role_user');

}

}


UserRole Model


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;



class UserRole extends Model

{

}



Now we can create records


$user = User::find(2); 

$roleIds = [1, 2];

$user->roles()->attach($roleIds);



$user = User::find(3);

$roleIds = [1, 2];

$user->roles()->sync($roleIds);



$role = Role::find(1);

$userIds = [10, 11];

$role->users()->attach($userIds);



$role = Role::find(2);

$userIds = [10, 11];

$role->users()->sync($userIds);



Now we can retrieve records


$user = User::find(1); 

dd($user->roles);



$role = Role::find(1);

dd($role->users);




Hence laravel Eloquent is more powerful and we do relationships easily compared to native query. We will be having three more relationships in laravel. Ie.., has many, one to many polymorphic and many to many polymorphic. With eloquent relationship we can easily connect the tables each other. One to one relationships we can connect two tables with their basic functionalities. In one to many we will connect with single table with multiple options. In Many to many we will be having more tables.
8731 views · 3 years ago


Welcome back! If you’re new to this series have a look at Part 1 here


Today’s focus is on templating, the aesthetic that will make or break your web application.

Having a clean design with well defined CSS that’s responsive and user friendly goes a long way.

Developers often stick to their lane but delving into templating will bode in your favor, you can indeed
create a functional and launch-worthy application all on your own!

Let’s jump into it!

Structured structure


Everything you tackle should be found with ease down the line. Therefore careful planning is fundamental to the success and sustainability of your project. You’ll also find that clearly defining your work lends itself to more productivity overall as you spend less that explaining your work during a handover / looking for a specific piece of code or resource. You’ll probably end up spending more time on actual work.
Finding your own unique pattern with file structure and CSS identifiers will also work in your favor as something unique to your process will most likely be easier to remember and form a tactile relationship with.

Our project’s current structure looks like this:



>If you need to backtrack, Part 1 is a great place to start!

In part 1, we created our index.php which displays info from our database.

Let’s take this a step further and create a header and a footer for our index.php

Create a file called header.php and save this to your includes folder.

Next, create a file called footer.php and save this to your includes folder.

Your file structure should now look like this.



A header above all the rest


The header file will be a file we reuse throughout your web application. This file will contain important information that’s vital to the functionality and aesthetic of your website.
The type of info you’ll expect to see in a header.php file:
Script includes
Such as JQuery and important libraries
CSS includes
CSS files loaded from internal or external sources
Meta information
Contains important information that’s readable by search engines.
The basic structure of the beginning of your app, including your menu, and your logo.
For now, how header is going to have a basic layout.

Let’s get our HTML on!

<html>
<head>
<title>My Awesome CMS – Page Title</title>
</head>
<body>


A footer that sets the bar

Create a file called footer.php and save it to your includes folder (yourcms/includes/footer.php).

Add this code to your new file.

</body>
</html>


Next, let’s focus on the gravy… The CSS


CSS, when written beautifully, can truly set you apart.

You can tell your web application to load various styles to specific elements by defining unique identifiers.
Styles that are only used once are denoted with a # (a CSS “ID”) whereas styles that are reused multiple times are denoted with a . (a CSS “class”)

The best way to delve into the realm of CSS is to learn by experience.

Let’s create!


First, we need to create and load our CSS file. Remember our nifty new pal header.php? This created a convenient way to load our CSS file!

Add the following code to your header.php just above the </head> tag.

<link href=”../assets/css/style.css” type=”text/css” rel=”stylesheet”/> 


The ../ in the link to our stylesheet means we have to leave the current directory (the directory that header.php is in) and look for the assets/css/ directories.

Go ahead and create the css folder under your assets folder.

Next we’re going to create some simple CSS to test things out.

It’s time to add some style!


We are going to create two divs.
A div is a divider / section in HTML.
Add this to your index.php (located in your CMS’ root folder) above the <?php tag.

<div id="myfirstid"></div>
<div class="myfirstclass"></div>
<div class="myfirstclass"></div>
<div class="myfirstclass"></div>
<div class="myfirstclass"></div>
<div class="myfirstclass"></div>


Then, create a CSS file

Add this:

#myfirstid{
Background:lightblue;
Font-family:Arial;
Font-size:44px;
Font-weight: Bold;
}
.myfirstclass{
Font-size:15px;
Color: darkblue;
}


Save your newly created CSS to assets/css/ as style.css.

Pulling it all together, let’s see what we can do!


Let’s apply what we just learned to our index.php. But first, we should add our header.php and footer.php files.

Including everyone


Add this to the top of your index.php file:

include(‘includes/header.php’);


Remove the <divs> we used for practice earlier, we have something better in store!

Add this to the bottom of your index.php:

include(‘includes/footer.php’);


Next, let’s modify our code so we can add some style to the data we retrieve from our database.

Modify the following line:
foreach($getmydata as $mydata){ echo "Title: "; echo $mydata['title']; echo "<br/>"; echo "Content: "; echo $mydata['content']; echo "<br/>"; echo "Author: "; echo $mydata['author']; echo "<br/>"; echo "<br/>";


as follows:
?>

<div id=”myfirstid”>
<?php
foreach($getmydata as $mydata){
echo "<div class=”myfirstclass”>Title: ";
echo $mydata['title'];
echo "<br/>";
echo "Content: ";
echo $mydata['content'];
echo "<br/>";
echo "Author: ";
echo $mydata['author'];
echo "</div><br/><br/>";
}?>
</div>
<?php


Your full index.php should now look like this:

<?php
include('includes/header.php');
include('includes/conn.php');

if ($letsconnect -> connect_errno) { echo "Error " . $letsconnect -> connect_error;

}else{

$getmydata=$letsconnect -> query("SELECT * FROM content");

?>
<div id="myfirstid">
<?php
foreach($getmydata as $mydata){
echo "<div class=”myfirstclass”>Title: ";
echo $mydata['title'];
echo "<br/>";
echo "Content: ";
echo $mydata['content'];
echo "<br/>";
echo "Author: ";
echo $mydata['author'];
echo "</div><br/><br/>";
}
?>
</div>
<?php
}

$letsconnect -> close();
include('includes/footer.php');
?>


Go ahead, test it out!

There’s a lot to unpack and I will break things down a little more during our next tutorial!

Challenge


Study the final index.php and try to form a few theories about why closing a php tag is necessary before adding raw html.

Next Up: #CodeWithMe Part 4: Building A Good Base

8334 views · 3 years ago
Laravel Eloquent Relationship Part 2

As you all know, Laravel Eloquent Relationships are powerful and easy methods introduced by Laravel for helping developers to reduce the complexity when connecting with multiple tables. While connecting with multiple tables, this method is very easy for developers for creating the application

Here you can see the next three methods of the eloquent relationships:
   
. Has Many Through Relationship
    . One to Many Polymorphic
    . Many to many Polymorphic

HAS MANY THROUGH ELOQUENT RELATIONSHIP

Has many through is a little bit complicated while understanding. I will provide a shortcut method to provide access data of another mode relationship. We will create a user table, post table, and country table and they will be interconnected with each other.

Here we will see Many through relationship will use hasManyThrough() for the relation


Create Migrations


Users table

 Schema::create('users', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('email')->unique();

$table->string('password');

$table->integer('country_id')->unsigned();

$table->rememberToken();

$table->timestamps();

$table->foreign('country_id')->references('id')->on('countries')

->onDelete('cascade');

});


Posts table

Schema::create('posts', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->integer('user_id')->unsigned();

$table->timestamps();

$table->foreign('user_id')->references('id')->on('users')

->onDelete('cascade');

});


Countries table

Schema::create('countries', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->timestamps();

});


Create Models


Country Model

<?php


namespace App;

use Illuminate\Database\Eloquent\Model;


class Country extends Model

{

public function posts(){

return $this->hasManyThrough(

Post::class,

User::class,

'country_id',
'user_id',
'id',
'id'
);

}

}


Now we can retrieve records by

$country = Country::find(1); 

dd($country->posts);


ONE TO MANY POLYMORPHIC RELATIONSHIP

One to many polymorphic relationships used one model belongs to another model on a single file. For example, we will have tweets and blogs, both having the comment system. So we need to add the comments. Then we can manage both in a single table


Here we will use sync with a pivot table, create records, get all data, delete, update, and everything related to one too many relationships.

Now I will show one too many polymorphic will use morphMany() and morphTo() for relation.


Create Migrations

Posts table

Schema::create('posts', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});

Videos Table

Schema::create('videos', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});

Comments Table

Schema::create('comments', function (Blueprint $table) {

$table->increments('id');

$table->string("body");

$table->integer('commentable_id');

$table->string("commentable_type");

$table->timestamps();

});


Create Models

Post Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


class Post extends Model

{



public function comments(){

return $this->morphMany(Comment::class, 'commentable');

}

}

Video Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


class Video extends Model{



public function comments(){

return $this->morphMany(Comment::class, 'commentable');

}

}

Comment Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model{



public function commentable(){

return $this->morphTo();

}

}


Create Records


$post = Post::find(1); 

$comment = new Comment;

$comment->body = "Hi Harikrishnan";

$post->comments()->save($comment);


$video = Video::find(1);

$comment = new Comment;

$comment->body = "Hi Harikrishnan";

$video->comments()->save($comment);



Now we can retrieve records


$post = Post::find(1); 

dd($post->comments);



$video = Video::find(1);

dd($video->comments);



MANY TO MANY POLYMORPHIC RELATIONSHIPS

Many to many polymorphic is also a little bit complicated like above. If we have a tweet, video and tag table, we need to connect each table like every tweet and video will have multiple persons to tag. And for each and every tag there will be multiple tweet or videos.

Here we can understand the creating of many to many polymorphic relationships, with a foreign key schema of one to many relationships, use sync with a pivot table, create records, attach records, get all records, delete, update, where condition and etc..


Here morphToMany() and morphedByMany() will be used for many to many polymorphic relationships

Creating Migrations

Posts Table

Schema::create('posts', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});

Videos Table

Schema::create('videos', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});

Tags table

Schema::create('tags', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});

Taggables table

Schema::create('taggables', function (Blueprint $table) {

$table->integer("tag_id");

$table->integer("taggable_id");

$table->string("taggable_type");

});


Creating ModelsPost Model


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model

{



public function tags(){

return $this->morphToMany(Tag::class, 'taggable');

}

}


Video Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Video extends Model

{



public function tags(){

return $this->morphToMany(Tag::class, 'taggable');

}

}

Tag Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model

{



public function posts(){

return $this->morphedByMany(Post::class, 'taggable');

}





public function videos(){

return $this->morphedByMany(Video::class, 'taggable');

}

}

Creating Records

$post = Post::find(1); 
$tag = new Tag;
$tag->name = "Hi Harikrishnan";
$post->tags()->save($tag);


$video = Video::find(1);
$tag = new Tag;
$tag->name = "Vishnu";
$video->tags()->save($tag);


$post = Post::find(1);
$tag1 = new Tag;
$tag1->name = "Kerala Blasters";
$tag2 = new Tag;
$tag2->name = "Manajapadda";
$post->tags()->saveMany([$tag1, $tag2]);


$video = Video::find(1);
$tag1 = new Tag;
$tag1->name = "Kerala Blasters";
$tag2 = new Tag;
$tag2->name = "Manajappada";
$video->tags()->saveMany([$tag1, $tag2]);


$post = Post::find(1);
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$post->tags()->attach([$tag1->id, $tag2->id]);


$video = Video::find(1);
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$video->tags()->attach([$tag1->id, $tag2->id]);


$post = Post::find(1);
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$post->tags()->sync([$tag1->id, $tag2->id]);


$video = Video::find(1);
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$video->tags()->sync([$tag1->id, $tag2->id]);



Now we can retrieve records

$post = Post::find(1); 
dd($post->tags);


$video = Video::find(1);
dd($video->tags)


$tag = Tag::find(1);
dd($tag->posts);


$tag = Tag::find(1);
dd($tag->videos);



Hence we completed all the relationships. In the above blog how has many through relationship, one to many polymorphic relationships and many to many polymorphic are working. This feature is introduced from Laravel 5.0 onwards and till the current version. Without the model, we can’t able to do this relationship. If we are using an eloquent relationship it will be very useful while developing an application.

    SPONSORS

    PHP Tutorials and Videos