Search code examples
phplaravelcrud

I got an unused variable in function Store in a controller, $variable = Model::create() (Laravel 9)


I would like to know how to use Model::create properly, because I don't have any issues, but I have an unused variable that someone explained to me that is normal and should stay there... it just doesn't make any sense for me.

That's my code.

public function store(StoreProjectRequest $request)
{
    $data = $request->validated();

    $slug = Project::genSlug($request->title);
    $data["slug"] = $slug;

    $newProject = Project::create($data);

    return redirect()->route("admin.projects.index");
}

If I hover the $newProject, it says "declared but not used".

Can anyone explain me?


Solution

  • The create method on a model returns an instance of the model that was created. If you do not use it anywhere after creating it, there is no point in assigning it to a variable. You can just do this:

    Project::create($data);
    

    A reason to assign it to a variable could be to redirect to a page that shows the information about the newly created model. Provided you have a route like this:

    Route::get('projects/{project}', [ProjectsController::class, 'show'])->name('projects.show');
    

    Something like this could make sense in your controller:

    public function store(StoreProjectRequest $request)
    {
        // ... validation
    
        $project = Project::create($data);
    
        return redirect()->route('projects.show', ['project' => $project]);
    }