Ad

Dynamically Use Of Model To Send Relationship Value In A View In Laravel

I am working on a bookmarking type of websites and want to show links related to their respective category on the category page. One link can only have one category.

I have created the model and view but having problem with the code of the controller to get data dynamically.

Links table

    {
        Schema::create('links', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('user_id');
            $table->text('link');
            $table->text('title');
            $table->text('description');
            $table->integer('category_id');
            $table->integer('votes');
            $table->dateTime('submitted_at');
            $table->rememberToken();
        });

Categories table

    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('slug');
            $table->string('status');
            $table->timestamps();
        });
    }

Category Model


use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
       protected $fillable = [
        'name', 'slug', 'status',
    ];
     public function links()
    {
        return $this->hasMany('App\Links');
    }
}

Links Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Links extends Model
{
    //
    protected $fillable = [
        'user_id', 'link', 'title', 'description', 'submitted_at', 'category_id','votes',
    ];

    public $timestamps = false;

    public function category()
    {
        return $this->belongsTo('App\Categories');
    }
}

Categories controller

public function index($slug)
    {
        $getcategoryid = DB::table('categories')->where('slug', '=', $slug)->get();
        $catid = $getcategoryid[0]->id;
        $catlinks=new \App\Category;
        $catlinks=$catlinks::find(1)->Links;
        return $catlinks;

The problem is I want find(1) to be dynamic according to the page. like if I can use $catid like find($catid) or something?

How can I get data to a category page if is has links then show and if not show a message no link found. like using count()

Ad

Answer

Seems like you are trying to load the links of a single category given a slug, you can do that like this:

// Do not forget to add this line after the namespace declaration
use App\Category;

public function index($slug)
{
    return Category::whereSlug($slug)->firstOrFail()->links;
}

But a nicer way would be to set up route model binding for your category model.

To do so, in your Category class put this method:

/**
 * Get the route key for the model.
 *
 * @return string
 */
public function getRouteKeyName()
{
    return 'slug';
}

Important: in your route file, make sure to replace the {slug} parameter of your route with {category} otherwise route model binding would not work at all.

Then in your controller class the index function would become:

public function index(Category $category)
{
    return $category->links;
}

You can read more about route model binding in the documentation


Updated answer

If you want to customize the response when the category doesn't exists you can do like the code below (in this case without using route model binding).

// Do not forget to add this line after the namespace declaration
use App\Category;

public function index($slug)
{
    $category = Category::whereSlug($slug)->first();

    if (! $category) {
        return response()->json([]);
    }

    return response()->json($category->links);
}
Ad
source: stackoverflow.com
Ad