Home > OS >  Attempt to read property "name" on null [ Laravel 8 ]
Attempt to read property "name" on null [ Laravel 8 ]

Time:09-03

i have a problem that my http://127.0.0.1:8000/admin/users/1 there's eror. I followed the tutorial exactly and i checked the coding a few times, i dont see any wrong on my code.

The name on <p >{{ $user->name }}</p> is null, i dont know how to fixed this. May i get your help?

<-- edit.blade.php -->

@extends('layouts.master')

@section('title', 'View User')

@section('content')
    
<div >

    <div >
        <div >
            <h4>Edit Users
                <a href="{{ url('admin/users') }}" >BACK</a>
            </h4>
        </div>
        <div >

            <form action="">
                <div >
                    <label>Full Name</label>
                    <p >{{ $user->name }}</p>
                </div>
                <div >
                    <label>Email Id</label>
                    <p >{{ $user->email }}</p>
                </div>
                <div >
                    <label>Full Name</label>
                    <p >{{ $user->created_at->format('d/m/Y') }}</p>
                </div>
            </form>

        </div>
    </div>
</div>

@endsection

<-- UserController -->

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();
        return view('admin.user.index', compact('users'));
    }

    public function edit($user_id)
    {
        $user = User::find('$user_id');
        return view('admin.user.edit', compact('user'));
    }
}

CodePudding user response:

You are using ' in find section please remove it :

public function edit($user_id)
{
    $user = User::find($user_id);
    return view('admin.user.edit', compact('user'));
}

CodePudding user response:

In your UserController in edit() method you are using single quote (') that is converting your variable as string. After that your model is generating query like below

select * from users where id='user_id'

this is not correct at all. Remove single quote from your find() method inside edit() method. Hope that you will get correct result according to need.

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();
        return view('admin.user.index', compact('users'));
    }

    public function edit($user_id)
    {
        $user = User::find($user_id'); //removed single quote(') from here
        return view('admin.user.edit', compact('user'));
    }
}
  • Related