I have Post model which has user function returning User model - creator of the post.
class Post extends Model
{
/**
* Get the user that owns the post.
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
In blade view I achieved how to print author name
{{ $post->user->name or 'Anonymous' }}
Above code works, but it is very hmm sensitive?
For example, I tried change this code to:
{{ $post->user->name, 'Anonymous' }}
<?php $post->user->name or 'Anonymous' ?>
Results? Trying to get property of non-object error on line with this code.
Maybe I am skipping something simple but important. How to print URL or default value in blade view. Pseudo code what I mean:
{{ '' or 'Anonymous' }}
Try
{{ isset($post->user->name) ? '' : 'Anonymous' }}
If this doesn't work (I haven't check it) try something like this:
#if (isset($post->user->name))
#else
Anonymous
#endif
Actually the error is not because the code is sensitive, it is because you are actually trying to access non objects values.
To achieve what you are looking for:
{{ isset($post->user)?'' : 'Anonymous' }}
Related
This question already has answers here:
Laravel Collection paginate does not exist
(2 answers)
Closed last year.
This is my controller file's index function
public function index()
{
$projects = Projects::All()->paginate( 5 );
return view('projects.index')->with('projects', $projects);
}
And, This is my blade file's pagination code
#foreach ($projects as $project)
{{ $project->links('pagination::tailwind') }}
#endforeach
But, Still, there's an error, that is saying
BadMethodCallException
Method Illuminate\Database\Eloquent\Collection::paginate does not exist.
You have a typo. This is not correct:
{{ $project->links('pagination::tailwind') }}
Error 1: You are missing a 's':
{{ $projects->links() }}
Error 2: You do not have to put your links in the loop but outside the loop. normaly after the loop.
#foreach($records as $record)
{{ $record->field }}
#endforeach
{{ $records->links() }}
Suggestion: I prefer to tell laravel which paginator I am using in this file:
App/Providers/AppServiceProvider.php
public function boot()
{
Paginator::useBootstrap(); //bootstrap in this case
}
For tailwind, there is no need to specify anything, since it is the default.
Background:
I installed a new Laravel version 8.49.2, and moved my app logic (controllers, routes, views, middlewares, models, custom configs) from (a legacy Laravel v5.8 project), Everything works well as expected so far.
But when I access a relationship attribute in blade I get the following error: Trying to get property 'title' of non-object (View: /Path/to/resources/views/users.blade.php)
Blade:
#foreach($users as $user)
<p> {{ $user->roles->title }} </p>
#endforeach
This
<p> {{ $user['roles']['title'] }} </p>
or
<p> {{ $user->roles['title'] }} </p>
Also gives the error Trying to access array offset on value of type null
The Controller:
$users = User::with(['roles'])->get();
return view('users', compact('users'));
User Model:
public function roles()
{
return $this->belongsTo(Role::class, 'levelId');
}
Role Model:
public function users()
{
return $this->hasMany(User::class, 'levelId');
}
When I die and dump dd($user->roles->title) I get the value "Admin"
But just echoing it like so {{ $user->roles->title }} gives the error.
NOTE:
When I change my PHP version to 7.3, this does not give an error. But in PHP 7.4.20 or 7.4.21 this error occurs. But I need PHP 7.4.*
Does anyone know how I can solve this?
Look like some users doesn't have role .So better check for null.When you dd($user->roles->title) it only check for first user record not for all users.
#foreach($users as $user)
<p> {{ $user->roles->title??null }} </p>
#endforeach
In my routes I have this route defined as:
// app/routes.php
Route::resource('CharacterController');
The corresponding method in the controller is:
// app/controllers/CharacterController.php
public function index(){
$characters = Character::all();
$houses = House::all();
return View::make('characters.index')->with(array('characters'=>$characters, 'houses' => $houses));
}
Finally, in the view:
// app/views/characters/index.blade.php
#this fires an error:
{{ $houses[$characters->house_id]->name }}
# at the same time this gives correct result:
{{ $houses[1]->name }}
# and this IS equal to 1:
{{ $characters->house_id }}
You can't use the id as index of the array to access the object with given id.
Since you have an Eloquent Collection you can use its various functions. One of them being find() for retrieving one item by id
{{ $houses->find($characters->house_id)->name }}
in MySql database i have systemSetting table and this have any data.
in this table i have this fields :
id - site_copyright - date
i want to fill form with this single row.
{{ Form::model($siteSettings) }}
{{ Form::label('site_copyright' , 'copy right') }}
{{ Form::text('site_copyright', null , array('id'=>'site_copyright' )) }}
{{ Form::label('site_copyright' , 'copy right') }}
{{ Form::text('site_copyright', null , array('id'=>'site_copyright' )) }}
{{ Form::close() }}
UPDATE:
in CONTROLLER of that i have this:
public function getIndex()
{
$siteSettings = SystemSetting::all();
return View::make('back_end.layouts.manageHeaders')->with('siteSettings', $siteSettings);
}
in Result, form could not parse data to input fields.
i get error for this :
$siteSettings->site_copyright
This is a duplicate of many questions, such as this: Laravel display table record using query
The short answer is: use first() method to get a single entry.
You're using form model binding, so change your controller to:
public function getIndex()
{
$siteSettings = new SystemSetting;
return View::make('back_end.layouts.manageHeaders', compact('siteSettings'));
}
Query work on 5.1 or more
return DB::table('users')->where('id', $id)->value('field_name');
//if lower version of laravel like 4.2
DB::table('users')->where('id', $id)->pluck('field_name');
I'm new to Laravel and I'm getting an error which I think has more to do with logic than anything else but I can't quite seem to grasp how to overcome it.
So, I have a page with a simple form to search for a particular string in my database. But I want to have the result show up on the same page.
Here's what I have so far:
This is my Route.php:
Route::get('/', 'HomeController#index');
Route::post('find', 'HomeController#find');
This is my HomeController:
public function index()
{
return View::make('index');
}
public function search()
{
return View::make('index');
}
public function find()
{
$match = Input::get('find');
if($match) {
$results = Book::where('title', 'like', '%'.$match.'%')
->orWhere('author', 'like', '%'.$match.'%')
->get();
return View::make('index', array('results', $results));
} else {
return Redirect::to('/')->with('flash_error', 'No string added!');
}
}
And my View (index.blade.php):
{{ Form::open(array('url' => 'find', 'method' => 'POST')) }}
{{ Form::text('find', '', array('class' => 'search-query', 'placeholder' => 'Search')) }}
{{ Form::submit('Submit', array('class' => 'btn btn-info')) }}
{{ Form::close() }}
#if (Session::has('flash_error'))
{{ Session::get('flash_error') }}
#endif
#foreach ($results as $result)
{{$result->title}}
#endforeach
(eventually the foreach will be replaced by some ajax loading to display each result)
And the error says "undefined variable: results" and shows the foreach.
I get why that error shows up since on the first pass to this page the results haven't been loaded yet but how can I overcome this? I really want the data to be shown on the same page without having to go to another page to display them.
Like I said, I think this is mostly logic related (although I'm very new to Laravel so it might be that too)
Any help would be greatly appreciated !
you need to pass an associative array as your second param of the make method
return View::make('index', array('results' => $results);
The problem here is that in your use of index.blade.php in multiple controllers, you forgot which controllers provide which variables (and as a result, which variables may be omitted).
When you request / (HomeController#index), index.blade.php is rendered, but since no $results are passed to the view, you see the Undefined Variable warning. This is not a problem in HomeController#find, because you define $results. To combat this, you'll need to do something along the lines of an isset() check on $results before you foreach over it. Like so:
#if(isset($results))
#foreach ($results as $result)
{{$result->title}}
#endforeach
#endif
Your logic may vary based on your page's layout (you might want to add an else and display some alternate placeholder content).
Also, if abstracting the call to View::make() with $results into index_gen() isn't keeping your code DRY, then I'd suggest replacing it in find() with the call to View::make().