php - Laravel - Fetch data using Auth

339

I want to fetch information of the logged in user stored in the database that is to be shown on his profile page. At the time of registration, he/she is been asked to enter the data and only a few fields are mandatory but in the 'edit profile' page he/she can add more information and then return to his profile page, where all the data should be updated. But the problem here is that only name and email is been fetched.

Controller code:

public function updateProfile(Request $req) {
        $name = Auth::user()->name;
        $user = Admin::where('name', $name)->first();
        if($req->input('admin-name')!= null) {
            $user->name = $req->input('admin-name');

        }

        if($req->input('admin-email')!= null) {
            $user->email = $req->input('admin-email');
        }
        if($req->input('admin-address')!= null) {
            $user->address = $req->input('admin-address');
        }
        if($req->input('admin-mobile')!= null) {
            $user->mobile = $req->input('admin-mobile');
        }
        if($req->input('admin-dob')!= null) {
            $user->dob = $req->input('admin-dob');
        }


        $user->save();


        return redirect('admin-profile')->with('update-response','Profile Updated successfully');
}

View:

<div >
          <h4>
          {{Auth::user()->name}}</h4>
          <small><cite title="">{{Auth::user()->address}} <i >
          </i></cite></small>
          <p>
            <i ></i>{{Auth::user()->email}}
            <br />
            <i ></i>Contact: {{Auth::user()->mobile}}
            <br />
            <i ></i>Born at {{Auth::user()->dob}}</p>  
        </div>
532

Answer

Solution:

You can just change the reference to the newly updated object ofuser to laravel instead of using the cached one, like this:

Auth::setUser($user);

Or you can work on yourAuth::user object directly, like this:

...
$user = Auth::user();
$name = $user->name;
...

Thanks but i have to redirect user's data to other view page

return redirect('admin-profile')->with([
    'update-response' => 'Profile Updated successfully', 
    'admin' => $user
]);

Then in yourview:

<h4>{{$admin->mobile}}</h4>
865

Answer

Solution:

Define an accessor in your User model.

class User extends Model{

    public function getMobileAttribute($value)
    {
        return $value;
    }
}

After this you can access it:

{{ Auth::user()->mobile }}

People are also looking for solutions to the problem: json - PHP Youtube downloader API Download file name videoplayback

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.