php - Load user settings from table

941

In Laravel 5.6, I have a settings table with auser_id.

I am trying to be able to link the\App\User class with the settings table.

I've got aSettings model with the following:

namespace App;
use Illuminate\Database\Eloquent\Model;
class settings extends Model
{
    protected $table = "settings";
}

And in my\App\User.php file I've got the following function:

public function settings() {
    $this->belongsTo(Settings::class);  
}

and at the top of that file i've gotUses App\Settings.

However when I run the following code in my master.blade.php template:

{{ dd(auth()->user()->settings()) }}

I just getnull. Why is this?

218

Answer

Solution:

in Your User Model :

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

In Your Blade :

 {{ Auth::user()->settings }}
130

Answer

Solution:

Try below Code :

Your Setting.php Model:

namespace App;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
    protected $fillable =['your_field1_name','your_field2_name','your_field_ect_name'];
    public function users() {
        return $this->hasMany('App\User');
    }
}

Your User.php Model :

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    protected $fillable =['your_field1_name','your_field2_name','your_field_ect_name'];
    public function settings() {
        $this->belongsTo('App\Setting');  
    }
}

Note:Your model name must be singular

$fillable : Protect against mass-assignment. A mass-assignment vulnerability occurs when a user passes an unexpected HTTP parameter through a request, and that parameter changes a column in your database you did not expect.

For more info visit :https://laravel.com/docs/5.6/eloquent#eloquent-model-conventions

People are also looking for solutions to the problem: php - Adding Jwt Booking Api file

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.