2

I am using Laravel 5.2 ..
There is a user and a profile table,it is a one-to-one relationship between them,
in ProfileController,
after user login,
when access create function,
if user's profile has not been created,return create page,
else,
redirect to edit function.

Question:
How to write the create function and edit function?
I writed a part of them.
1、how to write the parameter id in create function?
2、how to find the profile of the login user in edit function?

ProfileController:

    public function create()
    {
        $user = \Auth::user();
        if (!$user->profile) {
            return view('profile.create');
        }else{
           //how to write 'id'
           return redirect()->action('ProfileController@edit', ['id' => .......]);
        }
    }

    public function edit()
    {
       //how to find the profile of the login user?


       return view('profile.edit', compact('profile'));
    }
3
  • I’d instead create the corresponding profile record on User::create(): laravel.com/docs/master/eloquent#events Commented Feb 24, 2016 at 10:04
  • @MartinBean I don't understand,an example is better. Commented Feb 24, 2016 at 11:30
  • @sunshine I pointed you to the documentation, which has examples. Commented Feb 24, 2016 at 11:37

2 Answers 2

2

You need something like this:

public function create()
{
    $user = \Auth::user();

    if(isset($user->profile)) {
        return redirect()->action('ProfileController@edit', ['id' => $user->id]);
    }

    return view('profile.create');
}

// Get the current user
public function edit(App\User $user)
{
    if($user->id === \Auth::user()->id) {
        $profile = \Auth::user()->profile;

        return view('profile.edit', compact('profile'));
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

edit(App\User $user) you dont pass an instance you pass just an ID ['id' => $user->id]
@Froxz This is using route model binding in 5.2.
Ok got it) I'm still with 5.1))
There is an error:Missing required parameters for [Route: api.profile.edit] [URI: api/profile/{profile}/edit].
Yep you need to pass the user ID in the url.
|
1
$user = \Auth::user();

Same as you have in public function create() variable $user will contain info about current user

More you can create a constructor method like

use Illuminate\Contracts\Auth\Authenticatable;
protected $user;
public function __construct(Authenticatable $user){
   // $user is an instance of the authenticated user...
   $this->middleware('auth');
   $this->user = $user;
}
public function edit(){
   $user = $this->user;
}

Read DOCS

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.