Menu

Valuable tricks for Laravel Developers

I'm a Laravel developer and writing code for last 7 years and coding in Laravel for past 3 years. I am sharing few basic skills what I've seen most of the people are doing wrong while writing Laravel code. We have a lot of feature in Laravel but due to lack of our information and knowledge we keep using the old techniques. I am taking example of a blog website as it is easy to understand and everyone can relate to it. You can apply these methods according to your need. I will ask you some questions, try to find out their answer by your own first and then see the answers.


Question 1: I have to find the 4 trending posts for a blog website and my criteria to find is, the post having maximum number of comments will be considered as most trending. Try to write a query for that and then see the answer.

Answer: We all know, we make a one to many relation from Post to Comment in a blog website. So instead of writing foreach loops on each posts comment and counting them separately, we can use count function like this:

$trending_posts = Post::withCount('comments')
                    ->orderBy('comments_count', 'desc')
                    ->limit(4)
                    ->get();

Happy to save some time? Let's go to next


Question 2: Show all the posts title in a list and show No Posts found if database table is empty.

Answer: Most of the people uses a foreach loop or count the number of rows returned before the loop but why to do so much when we have a forelse loop in Laravel. forelse loop is much like foreach loop with an if condition. It will automatically detects if the returned variables has no results. You can use it in your blade view like this.

@forelse($posts as $post)
 <li>{{ $post->title }}</li>
@empty
  <li>No Posts Found</li>
@endforelse

If no record found for $posts then the empty section will be executed. You don't need to use any if statement or count() function.


Question 3: Whenever you make any changes in your environment file (.env). What do you do reflect the changes in the application.

Answer: Most of the people will re-run php artisan serve. That can do the work. But alternatively you can use:

php artisan config:cache

And you can see all the reflected changes. No need to re-run php artisan serve.


Question 4: How can you send a post request when you click an anchor tag href? Or How can you convert a get request to post request.?

Answer: This is a very frequent question asked to me by some junior developers. We all know anchor tags always hits a get request and have to do a little trick to accomplish the thing.

Suppose we have to logout a user by post request using a simple navigation anchor tag.


<a href="#" onclick="event.preventDefault(); document.getElementById('frm-logout').submit();">Logout</a>
<form id="frm-logout" action="{{route('logout')}}" style="display: none;" method="post" >
    {{csrf_field()}}
</form>


We will submit a hidden form on that click. This way we can convert a get request to post request.


Question 5: How can you fetch results from a table in a view only without using controller.

Answer: This is not a preferred way to fetch table results directly in a view but sometimes situation arises like this, when we have to do such tricks. It is most helpful when you need some table result in an included view, like header or footer. Otherwise you need to pass the variable from controller to each and every function. Better you should do this way. Suppose you need all the categories in header only.

So in header blade file. On the top line you can use

@php( $categories = \App\Category::all() )


Question 6: You are reading a blog post and below it, we want to show some other posts from the website to increase the engagement of the user as you see Related posts in most blogs. Let's take it this way, we have to show 4 random posts other than the post you're reading currently. How will you do this?

Answer: You can traverse all the post and use a if statement to check if the post_id is matching with the current post but you are using this method in core php also. Let's take some advantage of using Laravel. You can do like this:

$related_posts = Post::inRandomOrder()
                       ->limit(5)
                       ->get()
                       ->except($post->id);

So except() function can do the trick for you here.


Question 7: You are using a @foreach loop in the blade file and you have to check when will be a particular number of iteration occur. How will you do it?

Answer: Most of the developers use a count variable and keep increasing it with each iteration but we have a $loop variable inside the foreach loop in Laravel which keeps the count of iterations of the loop. You can use it either way, $loop->index will give you the count from 0 and $loop->iteration will give you the count from 1.

e.g. if you have to check the third post in the loop.

@foreach($posts as $post)
   @if($loop->iteration==3)
      dd('This is the third Post');
   @endif
@endforeach

You can use the $loop variable without declaring it anywhere.


These are some common mistakes I've seen people doing. I'll extend the list as i get more in my mind. You can suggest by commenting below.

Happy Reading.!

Posted In:
Laravel

0 Comments