#if control structure not recognized - php laravel 5 - php

I am programing a blog using Laravel 5 and bootstrap.
The #if control structure seem to not be working written this way in my blade.php:
#section('title')
#if($post)
<p> {{ $post->title}} </p>
#if(!Auth::guest() && ($post->name == Auth::user()->id || Auth::user()->is_admin()))
<button type="button" class="btn btn-default">Editer</button>
#endif
#endif
#endsection
Here is my function in PostController that calls the blade :
public function index()
{
$post = Post::get();
return view('posts.index', compact('post'));
}
I encounter this error :
Undefined property: Illuminate\Database\Eloquent\Collection::$title
I'm new to PHP, I can't seem to see where is the problem. If you have any clue, please help.

You need to attach a "post" variable when making a call to this view. In one of your controller methods.
In your edited question, "title" is missing. Pass a "title" variable along with post. Basically any variable you want to use in views that are not defined in view (except global variables), need to be passed to it explicitly from the controller.
Edit for collections error.
Your post variable is actually an array, loop through it and access title or any property of a post for each member of the post array

Related

Passing data from the database to a blade view using a controller in laravel

I found several ways to do what I need to do, the first way was using the rounting using the web.php file. But according to serveral posts this creates vulnerabilities in the application. So I found out the correct usage is with a controller that manages the database queries.
I created a controller, named EventsController and put this into it:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class EventsController extends Controller
{
public function index()
{
$events = DB::table('eventaries')->select('id','coursname','start', 'end', 'category')->get();
return view('components.course-list')->with('eventaries', $events);
}
}
the blade is inside the folder: /resources/views/components/course-list.blade.php
Inside the blade I use this code:
<div class="px-6 py-20">
<div class="max-w-7xl mx-auto">
<!-- Course List -->
{{ $events->coursname}}
</div>
</div>
But I get the error:
Undefined variable $events (View: D:\laragon\www\censored\resources\views\components\course-list.blade.php)
When using the with method on a view the first argument (key) becomes the name of the variable in the view and the second argument (value) becomes it's value.
This means you need to use $eventaries in your view instead of $events or rename the key in your controller return view('components.course-list')->with('events', $events);.
Also, I'm not sure about defining the action directly in the routes file causes vulnerabilities. I just think that the routes file, which is often the first entry point for developers when exploring a Laravel app, becomes hard to read/manage.
->with('eventaries', $events) means that you are passing the value of $events as eventaries. So in the blade you need to access it using $eventaries instead. So now blade code would be:
<div class="px-6 py-20">
<div class="max-w-7xl mx-auto">
<!-- Course List -->
{{ $eventaries->coursname}}
</div>
</div>
You have given 'eventaries' as the name for events. So you can only access it with $eventaries within the view, not as events.
you are passing to the view the value using the "with" method, and it does it like a value/key pair (->with($key, $value)). In your case you declare it like
return view('components.course-list')->with('eventaries', $events);
so, in the view you can access the value through the $eventaries, not the $events. Also, the query result is a collection and you will need to loop it to get each item
<div class="px-6 py-20">
<div class="max-w-7xl mx-auto">
<!-- Course List -->
#foreach($eventaries as $event)
{{ $event->coursename }}
#endforeach
</div>
</div>
What caused the issue?
The issue of this question was created because the router was never accessing the controller I created. I added the following code to my router to access the controller:
Route::get('/kursangebote/{course}', ['App\Http\Controllers\EventaryController', 'index'])->name('course.list-list');
In there I added the logic I wanted.
['App\Http\Controllers\EventaryController', 'index']
App\Http\Controllers\EventaryController is the controller I use, and index the function inside the controller I need to call. It might be a better Idea to use Eloquent for this https://laravel.com/docs/8.x/eloquent

Setting anchor link to an address in Laravel, gives error

In my Laravel application, when I am trying to link the username of the person who has posted in the website with his profile page, with the code:
<div class="media-body">#{{ post.user.name }}
It is giving the error:
Sorry, the page you are looking for could not be found.
1/1 NotFoundHttpException in RouteCollection.php line 161:
But, when I am trying to print #{{ post.user.profileUrl }} it is giving the right address, also in the json response, it is giving the right address, and going to the address is also reaching the specific location.
So, I don’t think it is some problem with post.user.profileUrl, as it seems to work fine, it seems to be some problem with using it with href, the address of the error in Google Chrome is:
http://localhost:8000/%7B%7B%20post.user.profileUrl%20%7D%7D
and the address should have been
http://localhost:8000/users/2 where 2 refers to the id of the user, which I am passing to the user through Vue.js
The problem is #{{ post.user.profileUrl }} is not parsing. %7B%7B%20post.user.profileUrl%20%7D%7D is ASCII representation of {{ post.user.profileUrl }}
Check if the code is in .blade.php file. If it is, you should look into JS template engine if you're using any.
https://laravel.com/docs/5.3/blade#blade-and-javascript-frameworks
The # symbol will be removed by Blade; however, {{ name }} expression will remain untouched by the Blade engine, allowing it to instead be rendered by your JavaScript framework
I think you have a $post model in your view. When you setup relationships between the model Post and User you can link to them through the following:
#{{ $post->user->name }}
This will turn the users profileUrl into a valid link. But therefor you had to setup relationships in the Models.
Post model:
public function user() {
return $this->hasMany('App\Users', 'id', 'user_id');
//first parameter is the Model class
//send is the id of the user table
//thirth is the user_id in the post table
}
And in the User model:
public function posts() {
return $this->hasMany('App\Posts', 'user_id', 'id');
}
Hope this works!
Try this... this should definitely work for you
#verbatim
<div class="media-body">
<a href="{{ post.user.profileUrl }}">
{{ post.user.name }}
</a>
</div>
#endverbatim
I got my problem, the issue is with the javascript library, I am using, known as vue.js, it used to allow usage inside quotes, but in vue 2, they don't, so there is a turnaround for this,
<a :href="post.user.profileUrl">#{{ post.user.name }}</a>
and this works fine.
Thanks to all the people who contributed by answering...

Laravel 5.1 flash message handling

In Laravel 5.0 and 4.* there was this option to check if the Session had flash_messages:
Controller:
public function store(Request $request) {
Session::flash('flash_message', 'Success');
return redirect('somepage');
}
And then you could call this in your layout:
#if (Session::has('flash_message'))
<p>{{ Session::get('flash_message') }}</p>
#endif
This worked perfectly fine, however in Laravel 5.1 it changed. Now it's stored in the request variable. So, I changed it in the controller to:
public function store(Request $request) {
$request->session()->flash('flash_message', 'Success');
return redirect('somepage');
}
And I call this in the layout:
#if($request->session()->has('flash_message'))
<p>{{ $request->session()->get('flash_message') }}</p>
#endif
I'm doing exactly what is stated in the Laravel 5.1 docs:
Determining If An Item Exists In The Session
The has method may be used to check if an item exists in the session.
This method will return true if the item exists:
if ($request->session()->has('users')) { // }
Now this works perfectly fine for store method now, because I only added a flash_message there, but if I want to access another method like index, create, edit, etc. it shows this error:
ErrorException
Undefined variable: request
I understand that the request variable is not declared in the other methods and I can workaround this if-statement using isset($request).
Is there a better solution to check if my flash_message is set in the $request variable like in the earlier versions of Laravel?
It sounds like you're using controllers generated by Laravel.
If you look at the method definitions for store and update you'll find the parameter Request $request. By including this Laravel automatically creates a Request instance for you.
In order to access this in other methods you have three options:
Add the same parameter to any of the other method definitions and Laravel will generate it for you in the same way.
Create a constructor function and have it assign a Request instance to an attribute.
public function __construct(Request $request)
{
$this->request = $request;
}
Declare use Session; before the class definition to make the Session class accessible in your namespace.
You can still use the old method :) . latest laravel just added new ways to achieve that goal.here goes the sample code to display error messages which are passed as flash message into a view page .
Sample code
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>Success</h4>
#if(is_array($message))
#foreach ($message as $m)
{{ $m }}
#endforeach
#else
{{ $message }}
#endif
</div>
#endif

Passing an id from a select list in a form, getting "non-object" error, Laravel-4

On a dashboard page, I've created a select list in a form that lists the names of components; the value that's passed from the select list is obviously the component id. On pressing submit, the user is routed to a page that displays the data about that component. Should be dirt simple...
Controller:
public function showDashboard()
{
$components = Component::lists('name','id'); ...
return View::make('dashboard', array('components'=>$components, ...))
}
dashboard.blade.php:
{{ Form::open(array('route' => array('components.show', $components->id), 'method'=>'get')) }}
{{ Form::Label('id','Component:') }}
{{ Form::select('id', $components) }}
{{ Form::submit('Show Component', array('class'=>'button')) }}
{{ Form::close() }}
I've tried various ways of doing this, and get a different error every time. The above code doesn't even let me display the dashboard page -- I get a "Trying to get property of non-object" error. Clearly, it's not liking $components because that was passed as a list array and not an object. As I said, I'm sure this is dirt simple, I just can't figure out the proper syntax, and Laravel docs aren't giving me the answer. Thanks!
The problem isn't the dropdown, or the lists method, but rather in your form opening. Here, you have $components->id as an argument to the route, but $components is an array and you can't access an id property on it.
Finally figured this out. I had posted a similar question here subsequent to this one, and rather than repeat the answer, it is here:
How to pass id value from select list to controller when controller expects an object? laravel-4
The very short version: change Route::get to Route::post. Details with code in the link above. Problem solved!

laravel 4: always the fourth controller method doesn't work->blank page

All the first three methods of all my controller work well, but when i add a fourth one this one doesn't work (the construct method not included) and give me a blank page with the url of the controller action.
my controller class:
class StoreController extends BaseController{
public function __construct(){
parent::__construct();
$this->beforeFilter('csrf', ['on'=>'post']);
}
public function getIndex(){
return View::make('store.index', ['products'=>Product::take(4)->orderBy('created_at','DESC')->get()]);
}
public function getView($id){
return View::make('store.view', ['product'=>Product::find($id)]);
}
public function getCategory($cat_id){
return View::make('store.category', [
'products'=>Product::where('category_id','=',$cat_id)->paginate(6),
'category'=>Category::find($cat_id)]);
}
public function getSearch(){
$keyword=Input::get('keyword');
return View::make('store.search', [
'products'=>Product::where('title','LIKE','%'.$keyword.'%')->get(),
'keyword'=>$keyword]);
}
}
In my route.php file:
Route::controller('store', 'Storecontroller');
And the triggerer form of the action is:
<div id="search-form">
{{ Form::open(['url'=>'store/search', 'method'=>'get']) }}
{{ Form::text('keyword', null, ['placeholder'=>'Search by keyword', 'class'=>'search']) }}
{{ Form::submit('Search', ['class'=>'search submit']) }}
{{ Form::close() }}
as I said the getSearch method doesn't work and I'm given a blank page with the url of the action (not the returned view)
thanks
As the page is blank, make sure that debug is set to true in your app config (should be the topmost setting, preferably in the local dir). This means that when an error occurs you will be shown an error page with a detailed stack trace and error message, making it easier for you to debug your app.
Make sure that the view store.search exists, is named correctly (check for typos) and contains the html/php you need to display the $products.
Next, you have two possibilities:
Set a default value for the keyword input
// For example:
Input::get('keyword', 'default')
Check if there is a keyword specified
// For example:
if (Input::has('keyword')) {...} else {...}
As a side note: You should not perform (heavy) tasks inside of arrays like you do here. Put them inside variables and include them into the view array like you did with the keyword variable. Your code will also be more readable and maintainable. There's a lot more about this, but thats of the point here.
Let me know if this helped you.

Categories