skip to Main Content

I have a problem with my code, I’m very new to this, so I’m having trouble finding the problem.

I want my categories to be displayed, so I can select one and assign it to the keyword, the site tells me that my categories are not defined

public function store(Request $request)
    {

        $motsCles = Mot_Cles::all();
        $categories = Categories::all(); 

        
        $request->validate([
            'mot' => 'required|string|max:255',
        ]);


        
        $motCle = Mot_cles::create([
            'mot' => $request->input('mot'),
        ]);

        $category = Categories::find($request->category);
        $motCle->categories()->attach($category);



        return view('Mots_Cles', compact('categories'));
        return view('Mots_Cles', compact('motsCles'));

    
        event(new Registered($motCle));
        return redirect(RouteServiceProvider::HOME);
    }

I tried to define the categories but everything seems to be fine, I wonder if it has something to do with the routes

2

Answers


  1. In your case, you have 3 return, only the first return fill be executed (https://www.php.net/manual/en/function.return.php). You can use multiple parameters in compact() function, sou you can maybe try this : return view('Mots_Cles', compact('categories', 'motsCles'));. I’m not totally sure to understand what you want to display, but it seems you are using Laravel, you can use dd(); function to learn what append in your variable and maybe find a solution or share what append to us.
    To help you to learn best practice in Laravel, I recommand you to read the documentation and you can check Laracast for more consistent example

    Login or Signup to reply.
  2. You use Model name wrong so first check the model name and second not use two return view-

    $motsCles = Mot_Cles::all();
    $categories = Categories::all(); 
    $request->validate([
        'mot' => 'required|string|max:255',
    ]);
    
    $motCle = Mot_Cles::create([
        'mot' => $request->mot,
    ]);
    
    $category = Categories::find($request->category);
    $motCle->categories()->attach($category);
    event(new Registered($motCle));
    if(event(new Registered($motCle));){
        return redirect('/home');
    }else{
        return view('Mots_Cles', compact(['categories','motsCles']));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search