7 Useful Laravel Tips and Tricks for Beginners

7 Useful Laravel Tips and Tricks for Beginners

Here are some awesome collection of Laravel Tips and Tricks for beginners in the topics like  Memory Optimization, Passing Route Parameters to the route() Helpers , How to Handle Relationships, Cache Database Queries,  Migrations, Blade Templating, Validation And User Input Sanitization To Prevent XSS Exploits etc.

1. Laravel Tips to Optimize Memory

Sometimes, you will need to process thousands of records. You realize that those operations are very substantial for your RAM, however Eloquent has a helpful strategy to chunk query results in blocks to optimize your load.

Appshop::chunk(200, function($shops)  {
      foreach ($shops as $shop)
      {
          // heavy operations on the shops here...
      }
  });

The first parameter defines the size of the block you need to utilize. For this situation, we will stack 200 results, handle them, unload them, and repeat the same thing with the following 200.

The second parameter is a closure that defines what to do with that chunk: the shops closure parameter is the returned collection of records.

2. Passing Route Parameters to the route() helper in Laravel

When your route has parameters (e.g. users/{id}), you have to define those parameters when you’re utilizing the route() helper to produce a connection to the route.

There are a couple of various approaches to pass these parameters. Let’s imagine a route defined as users/{userId}/comments/{commentId}. If the user ID is 1 and the comment ID is 2, let’s look at a few options we have available to us.

Option 1 :

route('users.comments.show', [1, 2])
// http://mysite.com/users/1/comments/2

Option 2 :

route('users.comments.show', ['userId' => 1, 'commentId' => 2])
// http://mysite.com/users/1/comments/2

Option 3 :

route('users.comments.show', ['userId' => 1, 'commentId' => 2, 'opt' => 'a'])
// http://myapp.com/users/1/comments/2?opt=a

3. Handle Relationships in Laravel

Handling Relationships in Laravel can’t be a easy task for beginners. Here are some useful laravel tips to make it easier. Let’s assume that we are searching for the document number of a specific user. We will utilize the User and identityDocument entities we just observed. For the purpose of this example, imagine that you have a table identityDocuments with the following columns:

  • Number: It indicates the document number
  • Type: It indicates the document type
  • due_date: It indicates the due date of the document
  • City: It indicates the city where the document was released

Here’s the code to get the document identity number, starting from a User instance:

$user = AppUser::where('first_name', '=', 'Sachin')->where('last_name', '=', 'Tendulkar')->first();
$identityDocumentNumber = $user->identityDocument->number;

If you echo $identityDocumentNumber, you will read the desired information.

Well, this is the way Laravel and Eloquent deal with querying your relationships. Once you have defined it, all you have to do is to access it as a simple property or a method.

Just execute the following query Now :

// the user Sachin Tendulkar as an ID = 11
  select * from users where first_name = 'Sachin' AND last_name = 'Tendulkar';
  select * from identityDocuments where user_id = 11

Now put the outcome into the $identityDocumentNumber. It is quite obvious for a one-to-one relationship; however, the same applies for a one-to-many relationship.

 

Let’s take another example :

$author = AppAuthor::where('first_name', '=', 'Rudyard')->where('last_name', '=', 'Kipling')->first();
  foreach($author->books as $book)
  {
    echo $book->title . <br/>;
  }

Output :
The Jungle Book
Kim
Just So Stories
Captains Courageous

As I let you know some time recently, you can have access to your relationship using a simple attribute or a method call. What’s the difference? Indeed, with the method call, you can do some filtering, and all that you saw some time recently, in order to get the desired result. In fact, you can raise a query on a relationship.

$author = AppAuthor::where('first_name', '=', 'Rudyard')->where('last_name', '=', 'Kipling')->first();
$theBooks = $author->books()->where('title', 'LIKE', '%the%')->get();
  foreach($theBooks as $book)
  {
    echo $book->title . <br/>;
  }

Output:
The Jungle Book

Accessing a pivot table

Working with many-to-many relationships, is not always about just defining a couple of external keys. You can put additional information into your pivot table in order to store some information for a specific connection between entities.

You already know how to create a pivot table, but how to access it? It’s nothing complex:   you should simply to use the pivot attribute of your relationship. Let’s take the below example:

First, you must define which attribute you want to take from the table, modifying the belongsToMany() call in your model:

return $this->belongsToMany('AppCategory')->withPivot('created_at', 'notes');

Then your code should be as follows:

$book = AppBook::find(27);
  foreach($book->categories as $category)
  {
    echo 'Association Date: ' . $category->pivot->created_at;
    echo 'Association Notes: ' . $category->pivot->notes;
  }

In the above example, we simply have printed all the dates that we appended a specific category to the book with id = 27. As an additional, we also printed some extra notes. This implies that on the pivot table, we have the created_at and notes fields.

Querying a relationship

Suppose you want to get all the authors who have at least one book in the database.

$authorsWithABook = AppAuthor::has('books')->get();

Now you want to find every author with at least five books in the database.

$authorsWithAtLeastFiveBooks = AppAuthor::has('books', '>=', 5)->get();

Okay, what about getting all the authors with at least one book dated 1994? Here we go, this time with the whereHas method:

 $authorsWithABookFromThe1994 = AppAuthor::whereHas('books', function($q)
  {
      $q->where('year', '=', 1994);
  })->get();

The first parameter indicates the name of the relationship you want to query. The second argument is a closure that takes a $q query parameter, which you can use to define conditions.

4. Cache Database Queries in Laravel

Too many database queries, and rapidly your application can become like molasses. Fortunately, Laravel offers a simple mechanism for caching these queries, using nothing more than a single method call.Here are Laravel Tips to Cache Database Queries.

Let’s grab all questions from the database, but cache the query, since it’s not likely that this table will be updated frequently.

$questions = Question::remember(60)->get();

Now, for the next hour of pages requests, that query will remain cached, and the database will not be touched.

5. Blade Templating in Laravel

PHP is by nature a templating language, it hasn’t hasn’t evolved to become an excessively good one. That is alright, however; Laravel offers its Blade engine to fill the gap. Simply name your views with a .blade.php extension, and they will automatically be parsed, accordingly. Now, we can do such things as:

@if ($orders->count())
    <ul>
        @foreach($orders as $order)
            <li>{{ $order->title }}</li>
        @endforeach
    </ul>
@endif

6. Migrations

To prepare the schema for a new users table, we may run:

php artisan migrate: make create_users_table

This will create a migration file, which you may then populate according to your needs. Once complete, php artisan migrate will create the table. That’s it! Need to roll back that creation? Simple! php artisan migrate:rollback.

Here’s an example of the schema for a frequently asked questions table.

public function up()
{
    Schema::create('faq', function(Blueprint $table) {
        $table->integer('id', true);
        $table->text('question');
        $table->text('answer');
        $table->timestamps();
    });
}

public function down()
{
    Schema::drop('faq');
}

Note : drop() method performs the inverse of up(). This is what allows us to rollback the migration.

7. Laravel Validation And User Input Sanitization To Prevent XSS Exploits

XSS Exploit is a well-known vulnerability in a web application whereby an attacker can inject client-side code into a web page. This can be done through user input areas such as search boxes, comments, posts, etc.

There are two types of XSS Exploits.

Non-Persistent mode : In this the malicious code is not permanent. Imagine a search box that returns results in response to the search query when the user clicks the Search button. In the event that an attacker were to infuse code in the search box, it would be executed just once (in response to the process of displaying the search results). A simple page refresh will wipe out the malicious code.

Persistent mode : In this the Injected malicious code is permanent. Assume we have a website  like 4chan, where anyone can create and read posts. An attacker infuses the code to initiate the attack. Since the post is saved (so that future visitors can read it), it will be executed every time someone lands on the page with the infected code.

Laravel Validation :

I have made an extremely easy to-do application utilizing the Laravel Docs. The user could add  and delete taska in the application. I won’t utilize controllers for such a small application and rather will create the functions directly in the routes.php file.

// Display All Tasks
Route::get('/', function () {
   $tasks = Task::orderBy('created_at', 'asc')->get();
    return view('tasks', [
       'tasks' => $tasks
   ]);
});

// Add A New Task
Route::post('/task', function (Request $request) {
   $task = new Task;
   $task->name = $request->name;
   $task->save();
    return redirect('/');
});

// Delete An Existing Task
Route::delete('/task/{id}', function ($id) {
   Task::findOrFail($id)->delete();
    return redirect('/');
});

Submit your Laravel Errors, issues or problems and get it fixed by a Laravel Expert