Six ways to perform a query

Submitted by luismec90 - 3 years ago

Laravel has many choices for performing a query, sometimes it could be confusing, I hope this list help you to clear any doubts. If you know other way please show it in comments for add it.

Given this tables:

Users
 id
 name

Posts
 id
 content
 user_id
 
Select all post from specific user:

    
    /* First Way */
    $user=User::find(1); // Just Eloquent
	$posts=$user->posts; // Just Eloquent
	
	/* Second  Way */
	$posts=User::with('posts')->find(1); // Eloquent with Eager loading


	/* Third  Way */
	$posts=User::find(1)->load('posts'); // Eloquent with Lazy Eager Loading


	/* Fourth  Way */
	$posts=User::join('posts','users.id','=','posts.user_id')->where('users.id',1)->get(); // Eloquent with Query Builder methods 


	/* Fifth  Way */
	$posts=DB::table('users')->join('posts','users.id','=','posts.user_id')->where('users.id',1)->get(); // Just Query Builder

	/* Sixth  Way */
	$posts=DB::select('select * from users join posts on users.id = posts.user_id where users.id = 1'); // Just SQL
comments powered by Disqus