Laravel - How to a try/catch in blade view? - laravel

I would like to create a way to compile in a view, the try/catch.
How can I do this in Laravel?
Example:
#try
<div class="laravel test">
{{ $user->name }}
</div>
#catch(Exception $e)
{{ $e->getMessage() }}
#endtry

You should not have try/catch blocks in your view. A view is exactly that: a representation of some data. That means you should not be doing any logic (such as exception handling). That belongs in the controller, once you’ve fetched data from model(s).
If you’re just wanting to display a default value in case a variable is undefined, you can use a standard PHP null coalescing operator to display a default value:
{{ $user->name ?? 'Name not set' }}

You are probably doing something wrong if you need a try..catch in your view. But that does not mean you should never do it. There are exceptions to every rule.
So anyway, here is the answer:
Put raw PHP in your view by using <?php ?> or #php #endphp tags. Then put your try..catch in the raw PHP.
#php
try {
// Try something
} catch (\Exception $e) {
// Do something exceptional
}
#endphp

while i agree with #areed that something is wrong if you have to use a try...catch, there are weird cases where a wrong approach can lead you down that path. One instance is using the same blade to house a paginate() and a get() response. Well, this might help a little.
<?php try{ ?>
//try to show something
{{ $products->links() }}
<?php }catch(\Exception $e){ ?>
// show something else
<?php } ?>

Related

How to write post response in Laravel?

How to convert this php code in to laravel?
While add this code in laravel blade getting error?
<?php
$status=$_POST["status"];
echo "<h3>Thank You. Your order status is ". $status .".</h3>";
?>
Laravel is an MVC framework, so the business logic remains in controller function like:
$status = Input::get('status');
and pass it to view like:
return view('view_name', ['status' => $status]);
and you can use this variable on view like:
<h3>Thank You. Your order status is {{ $status }}</h3>

Handling errors when variable is null - Laravel

I'm querying a model in a method in my controller to get all messages.
public function index(){
$messages = Message::where('sender_id', Auth::user()->id)->orWhere('recipient_id', Auth::user()->id)->get();
return view('/pages/message/index', compact('messages'));
}
If the model is null and has now entries, I get an error of 'can get method of non object or something like that.
What's the best way to handle errors like this. Ideallly in the controller
#if($messages)
//Codes
#endif
if collection in loop. Forelse statement is cool for that.
#forelse ($messages as $message)
<li>{{ $message->content }}</li>
#empty
<p>There is no messages</p>
#endforelse
in your view
#if(count($messages)>0)
//your code
#endif
or
#if(!empty($messages))
//your code
#endif

Laravel 5.4 Chaining to display Auth data

I have this in my master blade
<?php $user=auth()->user() ?>
{{ $user->id }}
Im using this code to display the ID of my user detail,
Can you suggest a way to remove <?php ?> or atleast a cleaner approach on this auth ?
Just use id() method:
{{ auth()->id() }}
If you need some other property or related data to display, use user() to get current user object:
{{ auth()->user()->name }}
Maybe you can do something like :
{{ auth()->user()->id }}
or if you have Laravel Auth
use Illuminate\Support\Facades\Auth;
Auth::id();
You can try above suggested answered as cleaner approach, but if you want to remove <?php ?>, you can try below code:
{{--*/ $user=auth()->user() /*--}}
I recommend to use above answered cleaner approach.
if you want to store user to variable initialize it on #php. For example
#php($user = auth()->user())
{{ $user->id }}

New to Laravel - How to pass model data to a blade view?

Ok, I am totally re-writing this question, now that I am a bit more familiar with larval.
Here is my situation: I have a guitar lessons site based on larval 5.2.36, where each lesson belongs to a category, and within a lesson are several exercises. An exercise table does not have a category id as it is linked to a lesson which has a category.
Goal What I am trying to figure out is how to pass the category of the currently displayed lesson or exercise to a menu sidebar view that displays the categories, so that the category of the lesson or exercise is highlighted. For this, I need to understand how to do such a task in laravel.
From what I gathered, this is often done via controllers. However, there is no menu controller, but rather a menu composer. It contains a function
class MenuComposer
{
public function compose(View $view)
{
$minutes = 6 * 60;
$value = Cache::remember('menu-categories', $minutes, function() {
return \App\Category::with('parent')->with('children')->get();
});
$view->with('categories', $value);
}
}
Then in the menu blade file we have
#foreach ($categories as $category)
<?php $category = $category->present(); ?>
#if ($category->parent == null)
<li>{{ $category->title }}</li>
#foreach ($category->children as $child)
<?php $child = $child->present() ?>
<li class="level1">{{ $child->title }}</li>
<?php
/*
#foreach ($child->children as $grandChild)
<?php $grandChild = $grandChild->present() ?>
<li class="level2">{{ $grandChild->title }}</li>
#endforeach
*/
?>
#endforeach
#endif
#endforeach
So this is clear. I see that I can use the menu composer to pass additional data with a $view->with() call.
The question is how do I get the current category? For exercises and lessons, the routes don't have category data. They are of form
lesson/lessonid/lessontitle
or
exercise/exid/extitle
So I know I could do some sort of query of the model. But seems that wouldn't make sense, since I know there are other places in the process flow where the current cat is being passed. For instance, on an exercise page, the view is retrieving category as
$exercise->lesson->category->title
It is being passed this in exercise controller as
public function index($id, $name = null)
{
//$this->hit($id);
$exercise = $this->apiController->get($id);
$authorized = $this->isUserAuthorized();
return view('exercise/index', [
'exercise' => $exercise->present(),
'authorized' => $authorized,
]);
}
Similarly, a lesson controller passes $lesson object to lesson view as
public function index($id, $name = null)
{
//$this->hit($id);
$lesson = $this->apiController->get($id);
$subscribed = $this->request->user() && $this->request->user()->subscribed('premium');
return view('lesson/index', [
'lesson' => $lesson->present(),
'subscribed' => $subscribed,
]);
}
Based on above, seems I could modify the return statements in the lesson and exercise controller to pass the category to the menu view, but I don't see in the documentation how to do that, and I suspect the menu view is rendered before the lesson and exercise controller are called...
Also read about using service providers. middleware, etc, here: How to pass data to all views in Laravel 5?
But all these approaches seem overkill. I don't need every view to have the data. Seems to me, I need to do this somehow in the menu composer. But I don't know what method to use from the menu composer to retrieve the current lesson or exercise category. In the menu composer after debugging in phpstorm I see that the $view object for a lesson has $view->$data->$lesson->$entity.
So what I did was edited the menu composer to pass category to view:
$d=$view->getdata();
$s=array_key_exists ('lesson' , $d );
if ($s ==1) $attr = collect($d)->get('lesson');
$cat=$attr->cat();
This works since in the LessonPresenter I added function
public function cat()
{
$cat = $this->entity->category['attributes']['title'];
return $cat;
}
This works, but I feel like it is a hack. And I will have to do this for the Exercise Presenter as well. Being new to larval I suspect there has to be a more elegant way to do this. So can someone please explain how this should be done?
thanks,
Brian
You can use Facades of Laravel directly in blade templates.
Just use {! !} syntax to try and echo it. e.g: {!! Route::current() !!}
There are also similar functions of Route facade you can use.
Then, you can check your category with #if() ... #endif blocks and add something like class name within it.
Note: Don't put lots of logic in your blade files. Do it in your controller file (even in your other service classes) and pass simplest variables (e.g $isCurrentCategory) as an array to your template files using View::make() function's 2nd parameter.
Maybe this can help you
<a href="#" class="{{ (\Request::route()->getName() == 'routename') ? 'active' : '' }}">
You can also get the route prefix for example, you can check this out here:
Laravel API Docs Routing

Laravel: Why isn't the query result showing in my view?

I am successfully getting results in/from my controller like this:
$session_id and $user_id are getting passed into my method.
Controller
// get all sets belonging to the user for the given session
$session = Session::findOrFail($session_id);
$sets = Set::where('session_id', $session_id)->where('user_id', $user_id);
$user = User::findOrFail($user_id);
return View('users.index')
->with('session', $session)
->with('sets', $sets)
->with('user', $user);
View
<p>{{ $user->first_name }} has {{ $sets->count() }} existing set{{ ($sets->count() > 1 ? 's': '') }}.</p>
<ul class="list-unstyled">
#foreach ($sets as $set)
<li>
Set
</li>
#endforeach
</ul>
I am seeing "Foo has 1 existing set." and I can see the record in the DB. However, I'm not getting into the loop at all. If I add/remove records, my paragraph text updates accordingly as well - but I still never get into the loop to show each set. I'm sure it's something obvious, but I sure don't see it.
Thank you for any suggestions!
Change the query of sets to this:
$sets = Set::where('session_id', $session_id)->where('user_id', $user_id)->get();
As get() method will return you the collection object.

Resources