isset is not working in laravel - laravel

I am sending a variable from controller to a view.
$message = "Thanks for Contacting";
return redirect('services')->with($message);
HTML
#isset ($message)
<a style="color: red;"> {{$message}} </a>
#endisset
But it shows en error, because when the first services is loaded from this route
Route::get('/services', function () {
return view('services');
});
There's no variable,so it gives en error. Please let me know what I am missing?

The problem is how you're passing the variable to your view.
the correct way is:
return view('services')->with('message', $message);
or
return view('services')->withMessage($message);
or
return view('services', ['message' => $message]);
or
return view('services', compact('message'));

You have to use it with #if,
Try this:
#if(session()->has('message'))
<a style="color: red;"> {{ session('message')}} </a>
#endif
and also change your controller like this:
return redirect('services')->with('message', $message);

The variable that set in redirect()->with() will saved to sessions variable, so to access it just call session() helper. Example:
#if (session('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
More explanation:
https://laravel.com/docs/5.6/redirects#redirecting-with-flashed-session-data

Related

in laravel error Invalid argument supplied for foreach() (View: i cant see $value

I am trying to make a blog foreach that see this erro
Invalid argument supplied for foreach() (View:
my site https://weadam.com/
my code is:
controller:
public function index()
{
$localetmp = Session::get('locale');
$blogs = #json_decode(file_get_contents("https://www.weadam.com/blogs/wp-json/wp/v2/posts?per_page=4&lang=" . $localetmp));
$blogsold = Blog::orderBy('id','desc')->take(100)->get();
foreach ((array)$blogs as $blog){
// $blog->elapsed = $this->time_elapsed_string('#'.$blog->date);
// $blog->date = date("d F Y",$blog->date);
}
$error = "";
return view('home-new',['blogs' => $blogs]);
}
and view is:
<div class="eng-home-blog">
<div class="col-sm-9 home-post-disp bx-shadow brd-radius bg-white">
#foreach($blogs as $blog)
#if($blog->sticky)
<img src="{{$blog->fimg_url}}" alt="" class="img-responsive brd-radius bx-shadow">
<div class="hm-post-date">{{$blog->date}}</div>
<h3>{{$blog->title->rendered}}</h3>
<p>{!!$blog->excerpt->rendered!!}</p>
<span>{{__("READ MORE")}}</span>
#endif
#endforeach
</div>
</div>
pass true as secondary param at json_decode function
$blogs = #json_decode(file_get_contents("https://www.weadam.com/blogs/wp-json/wp/v2/posts?per_page=4&lang=" . $localetmp),true);
now you have to fetch this blog data as associative data. not as an object. here's the example code for it
<div class="eng-home-blog">
<div class="col-sm-9 home-post-disp bx-shadow brd-radius bg-white">
#foreach($blogs as $blog)
#if($blog['sticky'])
<img src="{{$blog['fimg_url']}}" alt="" class="img-responsive brd-radius bx-shadow">
<div class="hm-post-date">{{$blog['date']}}</div>
#endif
#endforeach
</div>
</div>
You can simply use forelse it will take care of the empty case
#forelse($blogs as $blog)
// do what ever you want to do
#empty
<div> Nothing to show </div>
#endforelse
Hope it helps reference.
Thanks.

Undefined variable Laravel (strange case)

I am m having this annoying problem. Can anyone give a hand to sort out it? I read all posts and I cannot find the solution.
This is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use DB;
use App\Post;
use App\RegisteredCourse;
class DashboardsController extends Controller
{
public function indexA()
{
return view('dashboards.admin-dashboard');
}
public function indexS()
{
$id = Auth::user()->id;
$courses = DB::table('registered__courses')->select('user_id')->where('user_id', '=', $id)->count();
$posts = Post::all();
return view('dashboards.student-dashboard', compact('id', 'courses', 'posts'));
}
public function indexT()
{
return view('dashboards.teacher-dashboard');
}
}
This is a fragment of the blade view. The name of the view is dashboards.student-dashboard
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Posts</h3>
</div>
<div class="card-body">
<div class="tab-content">
<div class="active tab-pane" id="activity">
<!-- Post -->
<!--forEACH-->
#foreach ($posts as $post)
<div class="post">
<div class="user-block">
<span class="username">
{{$post->title}} | {{$post->author}}
</span>
<span class="description">{{optional($post->created_at)->format('d-m-Y')}}</span>
</div>
<!-- /.user-block -->
<p>
{{$post->content}}
</p>
</div>
#endforeach
</div>
</div>
</div>
</div>
</div>
And these are the routes
Route::group(['prefix' => 'dashboard',], function () {
Route::get('/admin', 'DashboardsController#indexA')->name('dashboards.indexA');
Route::get('/teacher', 'DashboardsController#indexT')->name('dashboards.indexT');
Route::get('/student', 'DashboardsController#indexS')->name('dashboards.indexS');
});
I tried to pass al the variable to the view and I always have the same problem. ("Undefined variable").It seems like blocked the possibility to pass variable to the blade view.
What I did before:
1-dd($posts) It does not working, it appears the exception "Undefined variable: posts".
2- I remove the whole content of the blade file and I tried with a simple varible and it stills appearing the exception "Undefined variable".
3- I ran php artisan view:clear and restarted the server.
Any sugestions?
Thank you very much.
Instead of
return view('dashboards.student-dashboard', compact('id', 'courses', 'posts'));
try
return view('dashboards.student-dashboard', ['id'=>$id, 'courses'=>$courses, 'posts'=>$posts]);

Laravel:Passing variable from controller to view

chatcontroller.php function returns variable to view:
public function getChat()
{
$message = chat_messages::all();
return View::make('home',compact($message));
}
this is my route:
Route::get('/getChat', array('as' => 'getChat','uses' => 'ChatController#getChat'));
this is my home.blade.php:
#extends('layouts.main')
#section('content')
<div class="container">
<h2>Welcome to Home Page!</h2>
<p> <a href="{{ URL::to('/logout') }}" > Logout </a></p>
<h1>Hello <span id="username">{{ Auth::user()->username }} </span>!</h1>
<div id="chat_window">
</div>
<input type="text" name="chat" class="typer" id="text" autofocus="true" onblur="notTyping()">
</div>
<ul>
#foreach($message as $msg)
<li>
{{ $msg['sender_username']," says: ",$msg['message'],"<br/>" }}
</li>
#endforeach
</ul>
<script src="{{ asset('js/jquery-2.1.3.min.js') }}"></script>
<script src="{{ asset('js/chat.js') }}"></script>
#stop
I am trying to send result returned by select query to view from controller.
when I do this from homecontroller.php then it works fine.
if I try to pass from controller which I have defined it gives error message as:Undefined variable.
I have used the extends \BaseController do i need to do anything else to access my controller variable from view.
please suggest some tutorial if possible for same.
Verify the route to be sure it uses the new controller:
Route::get('user/profile', array('uses' => 'MyDefinedController#showProfile'));
First of all check your routes, as Matei Mihai says.
There are two different ways to pass data into your view;
$items = Item::all();
// Option 1
return View::make('item.index', compact('items'));
// Option 2
return View::make('item.index')->with('items', $items); // same code as below
// Option 3
View::share('item.index', compact('items'));
return View::make('item.index);
You can also do this:
$this->data['items'] = Item::all();
return View::make('item.index', $this->data);

Laravel 4 return messages

Apologies Laravel newbee - on the learning curve.
In my controller I have
return Redirect::to('admin/categories/index')
->with('message', 'something went wrong');
How do I display this in my blade template? Are these known as 'flash messages'?
That is known as a redirect with flash data.
return Redirect::to('admin/categories/index')
->with('message', 'something went wrong');
With method flashes data to the session, you can retrieve it using Session::get in your View
#if(Session::has('message'))
<div class="alert-box success">
<h2>{{ Session::get('message') }}</h2>
</div>
#endif
I use this:
#if ( Session::has('message') )
<p class="alert">{{ Session::get('message') }}</p>
#endif
on the header of my base.blade.php

Laravel Redirect Back with() Message

I am trying to redirect to the previous page with a message when there is a fatal error.
App::fatal(function($exception)
{
return Redirect::back()->with('msg', 'The Message');
}
In the view trying to access the msg with
Sessions::get('msg')
But nothing is getting rendered, am I doing something wrong here?
Try
return Redirect::back()->withErrors(['msg' => 'The Message']);
and inside your view call this
#if($errors->any())
<h4>{{$errors->first()}}</h4>
#endif
Laravel 5 and later
Controller
return redirect()->back()->with('success', 'your message,here');
Blade:
#if (\Session::has('success'))
<div class="alert alert-success">
<ul>
<li>{!! \Session::get('success') !!}</li>
</ul>
</div>
#endif
Alternative approach would be
Controller
use Session;
Session::flash('message', "Special message goes here");
return Redirect::back();
View
#if (Session::has('message'))
<div class="alert alert-info">{{ Session::get('message') }}</div>
#endif
In Laravel 5.4 the following worked for me:
return back()->withErrors(['field_name' => ['Your custom message here.']]);
You have an error (misspelling):
Sessions::get('msg')// an extra 's' on end
Should be:
Session::get('msg')
I think, now it should work, it does for me.
Just set the flash message and redirect to back from your controller functiion.
session()->flash('msg', 'Successfully done the operation.');
return redirect()->back();
And then you can get the message in the view blade file.
{!! Session::has('msg') ? Session::get("msg") : '' !!}
In Laravel 5.5:
return back()->withErrors($arrayWithErrors);
In the view using Blade:
#if($errors->has())
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
In laravel 5.8 you can do the following:
return redirect()->back()->withErrors(['name' => 'The name is required']);
and in blade:
#error('name')
<p>{{ $message }}</p>
#enderror
For Laravel 5.5+
Controller:
return redirect()->back()->with('success', 'your message here');
Blade:
#if (Session::has('success'))
<div class="alert alert-success">
<ul>
<li>{{ Session::get('success') }}</li>
</ul>
</div>
#endif
in controller
For example
return redirect('login')->with('message',$message);
in blade file
The message will store in session not in variable.
For example
#if(session('message'))
{{ session('message') }}
#endif
I stopped writing this myself for laravel in favor of the Laracasts package that handles it all for you. It is really easy to use and keeps your code clean. There is even a laracast that covers how to use it. All you have to do:
Pull in the package through Composer.
"require": {
"laracasts/flash": "~1.0"
}
Include the service provider within app/config/app.php.
'providers' => [
'Laracasts\Flash\FlashServiceProvider'
];
Add a facade alias to this same file at the bottom:
'aliases' => [
'Flash' => 'Laracasts\Flash\Flash'
];
Pull the HTML into the view:
#include('flash::message')
There is a close button on the right of the message. This relies on jQuery so make sure that is added before your bootstrap.
optional changes:
If you aren't using bootstrap or want to skip the include of the flash message and write the code yourself:
#if (Session::has('flash_notification.message'))
<div class="{{ Session::get('flash_notification.level') }}">
{{ Session::get('flash_notification.message') }}
</div>
#endif
If you would like to view the HTML pulled in by #include('flash::message'), you can find it in vendor/laracasts/flash/src/views/message.blade.php.
If you need to modify the partials do:
php artisan view:publish laracasts/flash
The two package views will now be located in the `app/views/packages/laracasts/flash/' directory.
Here is the 100% solution
*Above mentioned solutions does not works for me but this one works for me in laravel 5.8:
$status = 'Successfully Done';
return back()->with(['status' => $status]);
and receive it as:
#if(session()->has('status'))
<p class="alert alert-success">{{session('status')}}</p>
#endif
It works for me and Laravel version is ^7.0
on Controller
return back()->with('success', 'Succesfully Added');
on Blade file
#if (session('success'))
<div class="alert alert-success">
{!! session('success') !!}
</div>
#endif
For documentation look at Laravel doc
I know this is an old post but this answer might help somebody out there.
In Laravel 8.x this is what worked for me: You can return the error to the previous page or to another page.
return Redirect::back()->withErrors(['password' => ['Invalid Username or Password']]);
This will also work:
return view('auth.login')->withErrors(['username' => ['Invalid Username or Password']]);
Please ENSURE, however, that the page/view you are returning has a field name that corresponds to the first parameter passed in the withErrors method (in this case, username or password) and that the #error directive in your view references the same field like this
#error('password') //or #error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
for example
Hope this helps somebody. Cheers.
#Laravel-9
Inside the blade where this redirection back action initiated
return redirect()->back()->with('message', "The Message");
Inside the blade where this form, will be returned after the above action
#if(session()->has('message'))
<p class="alert alert-success"> {{ session()->get('message') }}</p>
#endif
For laravel 5.6.*
While trying some of the provided answers in Laravel 5.6.*, it's clear there has been some improvements which I am going to post here to make things easy for those that could not find a solution with the rest of the answers.
STEP 1:
Go to your Controller File and Add this before the class:
use Illuminate\Support\Facades\Redirect;
STEP 2:
Add this where you want to return the redirect.
return Redirect()->back()->with(['message' => 'The Message']);
STEP 3:
Go to your blade file and edit as follows
#if (Session::has('message'))
<div class="alert alert-error>{{Session::get('message')}}</div>
#endif
Then test and thank me later.
This should work with laravel 5.6.* and possibly 5.7.*
I faced with the same problem and this worked.
Controller
return Redirect::back()->withInput()->withErrors(array('user_name' => $message));
View
<div>{{{ $errors->first('user_name') }}}</div>
In blade
#if(Session::has('success'))
<div class="alert alert-success" id="alert">
<strong>Success:</strong> {{Session::get('success')}}
</div>
#elseif(session('error'))
<div class="alert alert-danger" id="alert">
<strong>Error:</strong>{{Session::get('error')}}
</div>
#endif
In controller
for success
return redirect()->route('homee')->with('success','Successfully Log in ');
for error
return back()->with('error',"You are not able to access");
laravl 8
Route::post('/user/profile', function () {
// Update the user's profile...
return redirect('/dashboard')->with('status', 'Profile updated!');
});
Blade syntax
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
enter link description here
For Laravel 3
Just a heads up on #giannis christofakis answer; for anyone using Laravel 3 replace
return Redirect::back()->withErrors(['msg', 'The Message']);
with:
return Redirect::back()->with_errors(['msg', 'The Message']);
Laravel 5.6.*
Controller
if(true) {
$msg = [
'message' => 'Some Message!',
];
return redirect()->route('home')->with($msg);
} else {
$msg = [
'error' => 'Some error!',
];
return redirect()->route('welcome')->with($msg);
}
Blade Template
#if (Session::has('message'))
<div class="alert alert-success" role="alert">
{{Session::get('message')}}
</div>
#elseif (Session::has('error'))
<div class="alert alert-warning" role="alert">
{{Session::get('error')}}
</div>
#endif
Enyoj
I got this message when I tried to redirect as:
public function validateLogin(LoginRequest $request){
//
return redirect()->route('sesion.iniciar')
->withErrors($request)
->withInput();
When the right way is:
public function validateLogin(LoginRequest $request){
//
return redirect()->route('sesion.iniciar')
->withErrors($request->messages())
->withInput();
Laravel 5.8
Controller
return back()->with('error', 'Incorrect username or password.');
Blade
#if (Session::has('error'))
<div class="alert alert-warning" role="alert">
{{Session::get('error')}}
</div>
#endif
**Try This**
Try This Code
--- Controller ---
return redirect('list')->with('message', 'Successfully');
return redirect('list');
---- Blade view ------
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif

Resources