Trying to get property 'first_name' of non-object - laravel

I am trying to fetch digitizing order related to the user but unfortunately, I am facing an error.
Please see this error: https://flareapp.io/share/VmeWJ47Q
Controller
public function index()
{
$data=
[
'digitizings'=>Digitizing::with('user')->paginate(8)
];
return view('front_end.profile.digitizing.digitizing_view_order',$data);
}
User Model
class User extends Authenticatable
{
use Notifiable;
public function digitizing()
{
return $this->hasMany('App\Digitizing','user_id');
}
}
Digitizing Model
class Digitizing extends Model
{
protected $fillable = ['id','order_name','height','width','urgent','image',
'order_placement','required_format','order_fabric','instruction','user_id'];
protected $table ="digitizing_orders";
public function user()
{
return $this->belongsTo('App\User');
}
}
HTML view
#foreach($digitizings as $key =>$digitizing)
<tr>
<td>DPO# {{$digitizing->id}}</td>
<td>{{$digitizing->created_at}}</td>
<td>{{$digitizing->order_name}}</td>
<td>{{$digitizing->user->first_name}}</td>
<td>{{$digitizing->user->email}}</td>
<td>{{$digitizing->released_date ?? 'processing'}}</td>
<td>View
</td>
</tr>
#endforeach

Does every Digitizing-Entry has set a valid user_id in database? Try checking eager loaded data is set before accessing it.

Try to send the data to the view like this:
public function index()
{
$digitizings = Digitizing::with('user')->paginate(8);
return view('front_end.profile.digitizing.digitizing_view_order',$digitizings);
}

Related

laravel 8 store request with foreign key user_id not working

I would like to store the corresponding logged in user when adding a new School data. What I'm trying to do is store the logged in user_id in the schools table, in order to know on who added the school data. I have a users table already, which will establish the relation in the schools table.
My goal is when an admin is logged in, he/she can see all of the School records, otherwise if it's a user, then only fetch the records he/she added. The problem is that I can't figure out on when and where to insert the user_id data during the store request as I'm getting an error "user id field is required". Here's what I've tried so far:
Migration:
class CreateSchoolsTable extends Migration
{
public function up()
{
Schema::create('schools', function (Blueprint $table) {
$table->id();
$table->string('school_name');
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->timestamps();
});
}
}
School Model:
class School extends Model
{
use HasFactory;
protected $fillable = ['school_name', 'user_id'];
public function User() {
return $this->belongsTo(User::class);
}
}
Store Request:
class StoreSchoolRequest extends FormRequest
{
public function rules(): array
{
return [
'school_name' => 'required|string|max:255',
'user_id' => 'required|exists:users,id'
];
}
}
Controller:
class SchoolController extends Controller
{
public function store(StoreSchoolRequest $request) {
$school_data = $request->validated();
$user_id = \Auth::user()->id;
$school_data['user_id'] = $user_id;
School::create($school_data );
return Redirect::route('schools.index');
}
}
Any inputs will be of big help! Thanks.
Laravel has elegant way to bind authenticated user_id. Remove user_id from request class and chaining method. Also setup relationship from User model to School Model
Form Request Class
class StoreSchoolRequest extends FormRequest
{
public function rules(): array
{
return [
'school_name' => 'required|string|max:255',
];
}
}
User Model
protected $fillable = ['school_name', 'user_id'];
...
// new line
public function schools() {
return $this->hasMany(School::class);
}
Your Controller
class SchoolController extends Controller
{
public function store(StoreSchoolRequest $request) {
auth()->user()->schools()->create($request->validated());
return Redirect::route('schools.index');
}
}
UPDATE ANSWER
Since user_id value is school name (based on image link from comment), probably there's something wrong either in User or School model. Here the quick fix
Your Controller
class SchoolController extends Controller
{
public function store(StoreSchoolRequest $request) {
auth()->user()->schools()->create(
array_merge(
$request->validated(),
['user_id' => auth()->id()]
)
);
return Redirect::route('schools.index');
}
}
You can add 'created_by' and 'updated_by' fields to your table. so you can register in these fields when additions or updates are made.
Then you can see who has added or updated from these fields.
class School extends Model
{
use HasFactory;
protected $fillable = ['school_name', 'user_id', 'created_by', 'updated_by'];
public function User() {
return $this->belongsTo(User::class);
}
}
Your controller part is correct but since you get the logged in user, you wont be having user_id in the request. So you should remove the rules about user_id from your StoreSchoolRequest.
class StoreSchoolRequest extends FormRequest
{
public function rules(): array
{
return [
'school_name' => 'required|string|max:255'
];
}
}
Problem is here ..
$school_data = $request->validated();
Since you are using $request->validated()..
You have to safe()->merge user_id into it , here Docs : .
$validated = $request->safe()->merge(['user_id' => Auth::user()->id]);
Then put this $validated into create query , Thanks. –

Blank object in Eloquent belongsTo()

I'm trying to display which one attribute (code) of Item. ServiceItem has Item as a foreign key. But I can't get the Item at all.
This one gives a blank object in blade template:
#foreach ($service->serviceItems as $serviceItem )
{{ json_encode($serviceItem->item()) }}
#endforeach
Here's my model declaration:
//ServiceItem model
class ServiceItem extends Model
{
use HasFactory;
public $fillable = ['service_id', 'item_id', 'values'];
public function service()
{
return $this->belongsTo(Service::class, 'foreign_key');
}
// this doesn't work
public function item()
{
return $this->belongsTo(Item::class, 'foreign_key');
}
}
// Service model
class Service extends Model
{
use HasFactory;
public $fillable = ['user_id', 'site_id', 'title', 'status', 'remarks', 'report', 'date'];
public function user()
{
return $this->belongsTo('\App\Models\User');
}
public function site()
{
return $this->belongsTo('\App\Models\Site');
}
public function serviceItems() {
return $this->hasMany('\App\Models\ServiceItem');
}
}
This is my controller:
public function index()
{
$services = Service::latest()->paginate(5);
return view('services.index', compact('services'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
Please help me to display the code attribute in Item from Service!!! Thanks a lot!
I suppose you read the Laravel doc of model relationship definition. They referenced to put foreign key as the second parameter, not the foreign_key as word but your actual foreign key that reference the parent table. you have to change the model code.
class ServiceItem extends Model
{
use HasFactory;
public $fillable = ['service_id', 'item_id', 'values'];
public function service()
{
return $this->belongsTo(Service::class, 'service_id');
}
public function item()
{
return $this->belongsTo(Item::class, 'item_id');
}
}
and then $serviceItem->item should work as expected.

table data relation is not entered, encountered an error Method Illuminate \ Database \ Eloquent \ Collection :: links does not exist

Ticket.php
Protected $table = 'tickets';
Protected $fillable = ['user_id','kategori_id','judul','prioritas_id','status_id','message','file_tambahan'];
public function user()
{
return $this->belongsTo(User::class);
}
User.php
protected $table = 'users';
protected $fillable = [
'avatar','nama_lengkap', 'email', 'password',
];
public function getAvatar()
{
if(!$this->avatar)
{
return asset('images/default.png');
}
return asset('images/'.$this->avatar);
}
public function ticket()
{
return $this->hasMany(Ticket::class);
}
TicketController.php
use App\Model\Ticket;
use App\Model\User;
use App\Model\Kategori;
use App\Model\Prioritas;
use App\Model\Status;
class TicketController extends Controller
{
public function index()
{
$data = Ticket::with('User','Kategori','Prioritas','Status')->get();
return view('admin.crud_ticket.index', compact('data'));
}
index.blade.php
#foreach($data as $d)
<tr role="row" class="odd">
<td>{{ $d->user->nama_lengkap }}</td>
</tr>
#endforeach
{{ $data->links('vendor.pagination.custom') }}
I keep getting the same error over and over again, I do relationships between tables
namely in the user table, category, priority, status.
and cause an error like this, if you have a solution please help me
Method Illuminate\Database\Eloquent\Collection::links does not exist. (View: C:\xampp\htdocs\Helpdesk\resources\views\admin\crud_ticket\index.blade.php)

How to show record int profile related to user using Laravel?

I want to show record into user's profile related to user. I am trying to do this unfortunately it's not showing record related to user. How to do this?
Database
digitizing_orders table has user_id
Digitizingorder
class Digitizingorder extends Model
{
protected $table="digitizing_orders";
public function user()
{
return $this->belongsTo('App\User');
}
}
User Model
class User extends Authenticatable
{
public function digitizing()
{
return $this->hasMany('App\Digitizingorder','user_id');
}
}
controller
public function index()
{
$data=
[
'digitizings'=>Digitizingorder::with('user')->where('id','=',Auth::id())->get()
];
return view('front_end.Customerprofile.digitizing_view_order',$data);
}
#foreach($digitizings as $digitizing)
<tr>
<td>1</td>
<td>DPO-{{$digitizing->id}}</td>
<td>{{$digitizing->order_name}}</td>
<td>{{$digitizing->created_at}}</td>
<td>-</td>
<td>$0.00</td>
</tr>
#endforeach
Since you have a hasMany relationship you can get digitizings like so:
public function index()
{
$data=
[
'digitizings'=>Auth::user()->digitizing()->get()
];
return view('front_end.Customerprofile.digitizing_view_order',$data);
}
This will get the orders for the authenticated user.

Cannot Extend Laravel Model

I have 2 models. The User model, and the relationship works correctly, I use tinker, and I can see the application that is associated with the user.
User::find(4)->application
However, the application will not return the user - in tinker I get null, whats worse, if I try to access rep in tinker, I get Bad Method Exception Call
Application::find(8)->user
is null
Note: I have an id column in users which I "find" users. and there is "ucid" column in users that I have defined as the primaryKey in Application.
Application Model:
class Application extends Model
{
protected $data = [
'data' => 'array'
];
protected $primaryKey = 'ucid';
protected $fillable = [
'ucid', 'data'
];
public function user()
{
return $this->belongsTo(User::class,'ucid');
}
public function rep()
{
return 'Test';
}
}
User Model
class User extends Authenticatable
{
public function application()
{
return $this->hasOne(Application::class,'ucid');
}
}
What am I missing?
Can you try this? Let me know if it works..
Application Model
class Application extends Model
{
protected $data = [
'data' => 'array'
];
protected $primaryKey = 'ucid';
protected $fillable = [
'ucid', 'data'
];
public function user()
{
return $this->hasOne(User::class, 'ucid');
}
public function rep()
{
return 'Test';
}
}
User Model
class User extends Authenticatable
{
public function application()
{
return $this->belongsTo(Application::class, 'ucid', 'ucid');
}
}
As you see I switched hasOne and belongsTo in your models.
Also.. third argument on hasOne of Application Model is not required since value from $primaryKey will be used since its defined, however you have to specify the third argument in belongsTo of User model

Resources