Passing variable to view and capturing

Asked

Viewed 61 times

0

I have tried several ways to capture the variable I pass to the view, but without success.

Controlle

public function destroy($id)
{
    $retornoDestroy = $this->qpae->find($id);

    $delete = $retornoDestroy->delete();

    //Cria uma classe vazia StdClass
    $st = new \stdClass();

    if (isset($delete)) {

        $st->message = 'Apagado com sucesso!';

        return redirect()
            ->route('qpae-listar')->with('st', $st);                       

    }       
}

View

@if(isset($st))  
 <div id="msg" class="alert alert-sucess">                
  <p>{{$st}}</p>
 </div>
@endif

If deleted successfully, redirect and pass along the message $st, however, I cannot display this message in the view.

I’ve tried with:

@if(session('st'))  
 <div id="msg" class="alert alert-sucess">                
  <p>{{session('st')}}</p>
 </div>
@endif

That brings me back the error:

htmlspecialchars() expects Parameter 1 to be string, Object Given (0)

@if(session('st'))  
 <div id="msg" class="alert alert-sucess">                
  <p>{{$st->message}}</p>
 </div>
@endif

Undefined variable: st (0)


Solution

Controller

public function destroy($id)
{
    $retornoDestroy = $this->qpae->find($id);

    $delete = $retornoDestroy->delete();

    //Cria uma classe vazia StdClass
    $st = new \stdClass();

    if (isset($delete)) {

        $st->message = 'Apagado com sucesso!';

        return redirect()
            ->route('qpae-listar')->with('st', $st); **with sem colchete**                       

    }       
}

View

@if(session('st'))  
 <div id="msg" class="alert alert-success">                
  {{ session()->get('st')->message }}
 </div>
@endif
  • Your $st is an object, try to access an attribute of it like $st->message

  • I have tried too, unsuccessfully. Undefined variable: st (0)

  • What version of Laravel are you using? Try passing the parameter to the view by changing to ->with(['st', $st]);

  • Version 5.8.2. I tried this way ->with(['st', $st]); I don’t get any more errors in the view, but the message still doesn’t appear.

  • 1

    In the view you show the message this way: {{ session()->get( 'st' )->message }}

  • It worked! I showed using: {{ session()->get( 'st' )->message }} and had to remove the brackets of ->with(['st', $st]); getting ->with('st', $st);

  • Post then as solution of your post!

  • 1

    A tip: for messages of this type you can use the Flash Data of the Laravel.

Show 3 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.