How to check if a variable has data in laravel blade - php

I wanted to check if variable is there or not in blade ..for that i have used following lines:
#if(is_null($products))
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
//
#endforeach
#endif
The problem is when there is $products on blade I could show inside of foreach loop but when i get empty variable.I couldn't show the message No Data Found instead it shows only empty space?
is there any problem of checking variable inside of blade?
Controller code :
public function productSearch(Request $request)
{
$name = $request->name;
$products = Product::where('name' , 'like', '%'.$name.'%')->get();
return view('cart.product',compact('products'));
}

I generally use PHP count() :
#if(count($products) < 1)
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
//
#endforeach
#endif
You may also check with PHP empty() like :
#if(!empty($products))

As you can see in the documentation :
#forelse ($users as $user)
<li>{{ $user->name }}</li>
#empty
<p>No users</p>
#endforelse
This code will allow you to parse all the users and display a list of them. if the $users variables is empty, then it will display a paragraph
so for you :
#forelse ($products as $product)
//
#empty
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endforelse

As of Laravel 5.7, You can also do this:
#empty(!$products)
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endempty

You can check like
#if(isset($products) && !empty($products))
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
//
#endforeach
#endif

What about checking length?
#if(count($products)) >= 1)
#foreach($products as $product)
//
#endforeach
#else
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endif
Because empty set (i mean a data stucture with zero elements) is not null at all.
php > $a = [];
php > echo is_null($a) ? 1 : 0;
// => 0

is_null Finds whether the given variable is NULL or not. but in our case we need to check whether the value in empty or not for this you can use either isset() or empty() function both work same in your case
while isset — Determine if a variable is set and is not NULL and
empty — Determine whether a variable is empty and also tell variable is set
#if(isset($products) && !empty($products))
#foreach($products as $product)
//
#endforeach
#else
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endif

Do this,
Check is there any records "->count() > 0" then do foreach,
else alert.
#if ($products->count() > 0 )
#foreach($products as $product)
//enter code here
#endforeach
#else
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endif

For me I will use logic like this
if(!$products->isEmpty()){
return view('cart.product', compact('products'));
}else{
return view('pageerror', compact('products'));
}
then you can call pageerror from your view folder to display any page that does not has data

#forelse($products as $product)
<p>do some thing</p>
#empty
<p>No Products</p>
#endforelse
Refer

Try this
#forelse($products as $product)
//
#empty
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endforelse

I found the most effective (and by far the easiest way) of accomplishing what you're trying here to be as follows.
Assumption #1: You Know The Variable Exists Within The View.
REMEMBER: an empty array will always return false.
Therefore, there is no real need to run it through a function like empty or is null.
Comparing it to null will tell you if it exists or not.
(You could by-pass this assumption by checking to see if the variable is not equal to NULL (it's kind of bloaty if you've passed that variable through to the view, so in my opinion, I would KEEP IT SIMPLE STUPID [KISS] - if you want, you can go all fancy later when it comes to further refactoring).
ANYWAY..
I would stick to pretty similar code as you have now, maybe something like this here would be the code for your view:
#if(!$products)
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
// {{ $product . “code goes here.” }}
#endforeach
#endif
and the code for your controller would look something like this (you almost had it, remember: "perfect practice makes perfect!" - but yeah, the controller code:
public function productSearch(Request $request)
{
// Easily obtain the name submitted by the form (I assume via the request object
// dependency injection magic
$name = $request->name;
// I would consider using the DB builder tool, as follows, as there is more docs on it
// see: https://laravel.com/docs/5.6/queries - this will return a collection (iterable)
$products = DB::table(‘products’)
->where('name' , 'like', '%'.$name.’%’)
->get();
// simply passing to the view
return view('cart.product', compact('products'));
}
You would also need to include the Product model, DB (Laravel) and (as per usual) the request object, as follows:
// Laravel Dependencies
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
// User Created Model
use App\Product;
Hopefully, this has been helpful!

Related

Execute a value twice from the database

I have a strange problem, I am working on a personal project in Laravel, a "Q&A" type site, so far everything is fine. When I want to post a question from the database, it will be displayed twice on the display page, even if I only put the question with a certain id.
the error that appears
Route:
Route::get('/viewUserQuestion/{post}', 'PostsController#viewUserQuestion')->name('viewQuestion');
Controllerr:
public function viewUserQuestion() {
if(Auth::check()) {
$posts = Post::latest()->get();
return view('viewQuestion', compact('posts'));
}
else {
return redirect('register');
}
}
Blade:
<div class="card-body p-0">
#foreach($posts as $post)
<div class="mailbox-read-info">
<h5 align="center"> {{ $post->title }}</h5>
<h6> From userID: {{ $post->user_id }}</h6>
<span class="mailbox-read-time" align="center">Created at: {{ $post->created_at }}</span></h6>
</div><div class="mailbox-read-message">
<p>{{ $post->content }}</p>
Route to the display page:
<td>{{ $post->id }}</td>
What do you think would be the exact problem? I would be grateful if you could help me, does it run twice or does it?
Basically I want to display the data from each id, but in different pages without overlapping. As it is here, you click on a question and display it not twice.

Object of class Illuminate\Database\Eloquent\Collection could not be converted to int Laravel 5.4

I have an old database filled with info and now i want to display Category names from that DB and getting this error.
Here is my controller
public function forums(){
$cats = Forum_cats::all();
return view ('lapas.forums.index')->with('cats', $cats);
}
}
here is my view
#if(count($cats >1))
#foreach($cats as $cati)
<div class = "well">
<h3>{{$cati->description}}</hr>
</div>
#endforeach
#else
#endif
and here is screen of DB structure
http://prntscr.com/mg5nk1
Ask for more info if needed!
It looks like your operator is misplaced:
#if(count($cats) > 1)
#foreach($cats as $cati)
<div class = "well">
<h3>{{$cati->description}}</hr>
</div>
#endforeach
#else
#endif
It looks like you're trying to loop through these $cats in a Blade template. You might also try forelse:
#forelse($cats as $cati)
<div class = "well">
<h3>{{$cati->description}}</hr>
</div>
#empty
{{-- Action if there are none --}}
#endforelse
Edit: Docs here: https://laravel.com/docs/5.4/blade#loops
Your if is wrong. Try :
#if($cats->count() > 1)

Laravel show latest post on homepage

I'm trying to display the latest post, posted on my website.
I have a vague idea of how it needs to be done but I'm not 100% sure.
I think I need to do something like this in my PostController.php
public function index()
{
$laatstepost = Post::orderBy('created_at', 'desc')->take(1)->get();
return View('showposts')->with('laatsteposts', $laatstepost);
}
And then something like this in my view.
<div class="panel-body">
<h3>{{ $laatsteposts->title }}</h3>
<p>{{ $laatsteposts->text}}</p>
Lees meer...
</div>
I don't know if I'm heading the right way or that I'm completely off track. If u guys can help me out that would be great! Thanks
Here is a screenshot of where it needs to be displayed: http://imgur.com/a/c1feW
If I miss code that is needed for this, Tell me
Use the first() method to get an object instead of collection:
public function index()
{
$laatstepost = Post::latest()->first();
return view('showposts')->with('laatsteposts', $laatstepost);
}
And in the view:
<div class="panel-body">
<h3>{{ $laatsteposts->title }}</h3>
<p>{{ $laatsteposts->text }}</p>
Lees meer...
</div>
Alternatively, you can use your code to get a collection with just one element and display data in the view using first() collection method:
<div class="panel-body">
<h3>{{ $laatsteposts->first()->title }}</h3>
<p>{{ $laatsteposts->first()->text }}</p>
Lees meer...
</div>

Trying to get property of non object Laravel 5.2

The error occurs when i print the messages for the logged in user sent by others to him. I did var_dump in my controller as well as in my view. I also did {{$threads->count()}} in my view and it showed 27(thread count). But when i access the view file it throws me the above mentioned error.
Here is my controller code
public function index()
{
$currentUserId = Auth::user()->id;
$threads = Thread::getAllLatest()->get();
return view('chatindex', compact('threads', 'currentUserId'));
}
I also printed the currentUserId in view and it also works fine
Here is my view code (where the error occurs)
#extends('layouts.app')
#section('content')
#if (Session::has('error_message'))
<div class="alert alert-danger" role="alert">
{!! Session::get('error_message') !!}
</div>
#endif
#if($threads->count() > 0)
#foreach($threads as $thread)
<?php $class = $thread->isUnread($currentUserId) ? 'alert-info' : ''; ?>
<div class="media alert {!!$class!!}">
<h4 class="media-heading">{!! link_to('messages/' . $thread->id, $thread->subject) !!}</h4>
<p>{!! $thread->latestMessage->body !!}</p>
<p><small><strong>Creator:</strong> {!! $thread->creator()->name !!}</small></p>
<p><small><strong>Participants:</strong> {!! $thread->participantsString(Auth::id()) !!}</small></p>
</div>
#endforeach
#else
<p>Sorry, no threads.</p>
#endif
#stop
It throws me the error Trying to get property of non-object (View: C:\xampp\htdocs\laravel-projects\user_prof\resources\views\chatindex.blade.php)
maybe in your foreach $thread is an array() so use it like one as
$thread['id'], $thread['subject']

Laravel 5.2 redirect back with success message

I'm trying to get a success message back to my home page on laravel.
return redirect()->back()->withSuccess('IT WORKS!');
For some reason the variable $success doesn't get any value after running this code.
The code I'm using to display the succes message:
#if (!empty($success))
<h1>{{$success}}</h1>
#endif
I have added the home and newsletter page to the web middleware group in routes.php like this:
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', function () {
return view('home');
});
Route::post('/newsletter/subscribe','NewsletterController#subscribe');
});
Does anyone have any idea why this doesn't seem to work?
You should remove web middleware from routes.php. Adding web middleware manually causes session and request related problems in Laravel 5.2.27 and higher.
If it didn't help (still, keep routes.php without web middleware), you can try little bit different approach:
return redirect()->back()->with('message', 'IT WORKS!');
Displaying message if it exists:
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
you can use this :
return redirect()->back()->withSuccess('IT WORKS!');
and use this in your view :
#if(session('success'))
<h1>{{session('success')}}</h1>
#endif
Controller:
return redirect()->route('subscriptions.index')->withSuccess(['Success Message here!']);
Blade
#if (session()->has('success'))
<div class="alert alert-success">
#if(is_array(session('success')))
<ul>
#foreach (session('success') as $message)
<li>{{ $message }}</li>
#endforeach
</ul>
#else
{{ session('success') }}
#endif
</div>
#endif
You can always save this part as separate blade file and include it easily.
fore example:
<div class="row">
<div class="col-md-6">
#include('admin.system.success')
<div class="box box-widget">
You can simply use back() function to redirect no need to use redirect()->back() make sure you are using 5.2 or greater than 5.2 version.
You can replace your code to below code.
return back()->with('message', 'WORKS!');
In the view file replace below code.
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
For more detail, you can read here
back() is just a helper function. It's doing the same thing as redirect()->back()
One way to do that is sending the message in the session like this:
Controller:
return redirect()->back()->with('success', 'IT WORKS!');
View:
#if (session()->has('success'))
<h1>{{ session('success') }}</h1>
#endif
And other way to do that is just creating the session and put the text in the view directly:
Controller:
return redirect()->back()->with('success', true);
View:
#if (session()->has('success'))
<h1>IT WORKS!</h1>
#endif
You can check the full documentation here: Redirecting With Flashed Session Data
I hope it is very helpful, regards.
All of the above are correct, but try this straight one-liner:
{{session()->has('message') ? session()->get('message') : ''}}
In Controller
return redirect()->route('company')->with('update', 'Content has been updated successfully!');
In view
#if (session('update'))
<div class="alert alert-success alert-dismissable custom-success-box" style="margin: 15px;">
×
<strong> {{ session('update') }} </strong>
</div>
#endif
You can use laravel MessageBag to add our own messages to existing messages.
To use MessageBag you need to use:
use Illuminate\Support\MessageBag;
In the controller:
MessageBag $message_bag
$message_bag->add('message', trans('auth.confirmation-success'));
return redirect('login')->withSuccess($message_bag);
Hope it will help some one.
Adi
in Controller:
`return redirect()->route('car.index')->withSuccess('Bein ajoute')`;
In view
#if(Session::get('success'))
<div class="alert alert-success">
{{session::get('success')}}
</div>
#endif

Categories