Models: Retrieving the seller’s information

Intro: Take a look at the product details page, we need the name, the email, and the phone number of the seller to display here. Those data are there on the users table. And in the products table, for each product, we have the user id of the user who has created the ad for the product. We now have to find a way to retrieve the user’s data from the users table by the user id that we have inside the product details page. And this is pretty easy in Laravel as Laravel uses Eloquent ORM. So let’s get started.

Steps:

1. Eloquent makes managing and working with relationships between database tables easy.

2. Models are magical classes: We have been working with models for a while now. We have used an instance of a product model to add a new product ad to the products table, we have called functions like all(), find(), save() on an instance of a model. Now open the file Product.php from the folder app/Models …. SURPRIZED!! …. there is nothing inside, almost nothing. All the work of communicating with the corresponding database table is performed by Eloquent under the hood.

3. Add a function to establish the relationship:
Now we are trying to find a way to find the information of the seller for a product, for that we simply have to add a function inside the Product model, the name of this function should match the name of the model we are trying fetch so let’s name it user() here.
A user owns the product, or we may also say that a product belongs to a user. So here inside the function user(), we have to call a function named belongsTo() and pass the class name of the model to this function, and finally, we have to return the result.
return $this->belongsTo(User::class);
Now this works as the primary key of the users table is named id and the foreign key on the products table is named user_id ( _id appended to the snake case name of the parent model). If the foreign key on the products table were different than user_id , then we would need to pass it to the second argument of the belongsTo() function.
return $this->belongsTo(User::class,'foreign_key');
And if the name of the primary key on the users table were not id, then we would need to pass the primary key name to the third parameter of the function.
return $this->belongsTo(User::class,'foreign_key','primary_key');
In our case, we don’t need these second and third parameters as… the foreign key on our products table is user_id and it maps to the column id of the users table and this column id is the primary key of the users table. Eloquent understands this naming convention by default.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    /**
     * Get the user that has posted the add for the product.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

4. Now open the view for the product details page, (product.blade.php) and scroll down to the ‘seller information’ section.
Here replace the static string for the name with the actual name of the seller. We can treat the function user() of the Product model like a property of the class. So {{$product->user->name}} gives us the name of the seller, {{$product->user->phone}} give the phone and {{$product->user->email}} gives us the email of the user.

<x-base-layout>
  <!-- Main content -->
      <div class="flex m-4">
        <!-- Left half -->
        <div class="w-1/2 rounded overflow-hidden shadow">
          <img class="object-cover w-full" src="{{asset($product->image_url)}}"/>
        </div>
        <!-- Right half -->
        <div class="w-1/2 rounded bg-white ml-2 p-6 shadow relative">

            <div class="font-semibold">{{$product->title}}</div>
            <div class="text-sm text-gray-500">{{$product->short_desc}}</div>
            <div class="text-xs text-gray-500 mt-2">{{$product->long_desc}}</div>

            <!-- Seller Information -->
            <div class="mt-4">
              <div class="text-xs text-gray font-semibold">Sold by:</div>
              <div class="text-sm text-gray-500">{{$product->user->name}}</div>
            </div>
            <div class="mt-2">
              <div class="text-xs text-gray font-semibold">Phone number:</div>
              @auth
                <div class="text-sm text-gray-500">{{$product->user->phone}}</div>
              @else
                <div class="text-sm text-gray-500">**********<a href="/login" class="text-xs text-blue-500">(Login to view)</a></div>
              @endauth
            </div>
            <div class="mt-2">
              <div class="text-xs text-gray font-semibold">Email address:</div>
              @auth
                <div class="text-sm text-gray-500">{{$product->user->email}}</div>
              @else
                <div class="text-sm text-gray-500">**********<a href="/login" class="text-xs text-blue-500">(Login to view)</a></div>
              @endauth
            </div>

            <!-- Product Price -->
            <div class="absolute bottom-0 right-0 bg-green-500 px-4 py-2 m-6 rounded-full">
              <div class="text-white font-bold text-sm">${{$product->price}}</div>
            </div>

        </div>
      </div>
</x-base-layout>

After replacing the static strings with these values, open the details page for a product, and you’ll find the actual contact information of the seller.

Here the phone number is missing as this product was added by the previous user account for which we don’t have the phone number on the users table. Let me add one manually from phpMyAdmin.

(Now we have one more issue, the link to the image seems to be broken. To find out the issue let us right-click here and click on inspect, and notice the URL. As we have simply added the path of the image, it gets appended to the route and it worked on the home screen as the route, in that case, pointed to the root. And this can be easily fixed with help of the helper function asset() of Laravel. Instead of passing the image path directly to the href attribute, pass it to the asset() function and pass that result to the href attribute. The asset() function will create the appropriate URL for us.

Now reload the page, and we can see the image. )

Leave a Reply

Your email address will not be published.