Trying to get property 'post_titile' of non-object - laravel

This is My Controller.
public function show(Posts $posts)
{
$page = Posts::find($posts->id);
//dd($page);
return view('web_views.index',['page' => $page]);
}
This is my view page
<h4>{{$page->post_titile}}</h4>

It's better to use Route-Model Binding I think.
Your route (if you are using resource route, it's already done):
Route::get('posts/{post}', 'PostController#show); // domain.tld/posts/1
Your method should look like this:
public function show(Post $post)
{
return view('web_views.index',compact('post'));
}
In your view:
<h4>{{ $post->post_titile }}</h4>

May be $posts->id you are passing, has no result in database so you need to check it by using if-statement
public function show(Posts $posts)
{
$page = Posts::find($posts->id);
if($page == null){
$page = ['post_title' => 'Not Available'];
}
return view('web_views.index',['page' => $page]);
}
I believe this error is because of not finding data for an ID into database. So if as per above script will pass the fetched data to view otherwise it will push an item into $page array.

Related

Accessing $this->request in view without having to pass it into view Codeigniter 4

Is there a way of accessing the incomingRequest class within a view without having to pass it in a data array.
for instance I did the following initially:
public function location()
{
$request = \Config\Services::request()->getUri();
$data['uri'] = $this->request->uri;
return view('/path/to/view', $data);
}
But is there no nice way of accessing $this->request directly in the view without having to pass it into view
I want to do something like this:
<?php
$colorClass = $this->request->uri->getSegment(1) == 'workflow' ? 'bg-warning' : '';
?>
<nav class="<?= $colorClass ?>" >
<!-- rest of code here -->
</nav>
without having to pass the request directly to the $data array.
You can make your own helper function to return segment value.
if (!function_exists('getSegment')) {
function getSegment(int $number)
{
$request = \Config\Services::request();
if ($request->uri->getTotalSegments() >= $number && $request->uri->getSegment($number)) {
return $request->uri->getSegment($number);
} else {
return false;
}
}
}
Reference link: https://forum.codeigniter.com/showthread.php?tid=74755&pid=371243#pid371243

Why does the old() method not work in Laravel Blade?

My environment is Laravel 6.0 with PHP 7.3. I want to show the old search value in the text field. However, the old() method is not working. After searching, the old value of the search disappeared. Why isn't the old value displayed? I researched that in most cases, you can use redirect()->withInput() but I don't want to use redirect(). I would prefer to use the view(). method
Controller
class ClientController extends Controller
{
public function index()
{
$clients = Client::orderBy('id', 'asc')->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
public function search()
{
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
$query = Client::query();
if (isset($clientID)) {
$query->where('id', $clientID);
}
if ($status != "default") {
$query->where('status', (int) $status);
}
if (isset($nameKana)) {
$query->where('nameKana', 'LIKE', '%'.$nameKana.'%');
}
if (isset($registerStartDate)) {
$query->whereDate('registerDate', '>=', $registerStartDate);
}
if (isset($registerEndDate)) {
$query->whereDate('registerDate', '<=', $registerEndDate);
}
$clients = $query->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
}
Routes
Route::get('/', 'ClientController#index')->name('client.index');
Route::get('/search', 'ClientController#search')->name('client.search');
You just need to pass the variables back to the view:
In Controller:
public function search(Request $request){
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
...
return view('auth.client.index', compact('clients', 'clientID', 'status', 'nameKana', 'registerStartDate', 'registerEndDate'));
}
Then, in your index, just do an isset() check on the variables:
In index.blade.php:
<input name="clientID" value="{{ isset($clientID) ? $clientID : '' }}"/>
<input name="status" value="{{ isset($status) ? $status : '' }}"/>
<input name="nameKana" value="{{ isset($nameKana) ? $nameKana : '' }}"/>
...
Since you're returning the same view in both functions, but only passing the variables on one of them, you need to use isset() to ensure the variables exist before trying to use them as the value() attribute on your inputs.
Also, make sure you have Request $request in your method, public function search(Request $request){ ... } (see above) so that $request->input() is accessible.
Change the way you load your view and pass in the array as argument.
// Example:
// Create a newarray with new and old data
$dataSet = array (
'clients' => $query->paginate(Client::PAGINATE_NUMBER),
// OLD DATA
'clientID' => $clientID,
'status' => $status,
'nameKana' => $nameKana,
'registerStartDate' => $registerStartDate,
'registerEndDate' => $registerEndDate
);
// sent dataset
return view('auth.client.index', $dataSet);
Then you can access them in your view as variables $registerStartDate but better to check if it exists first using the isset() method.
example <input type='text' value='#if(isset($registerStartDate)) {{registerStartDate}} #endif />

Problem on setting error message if insert fails

When doing add activity inside store method, after passing validation I am calling a method that returns success or failure.
But on failure, I am not able to handle the code properly.
If I redirect, am not getting the old value.
So How do i return to create method with error message & old value both?
Any way to populate the $errors array?
Am new to Laravel. Thanks in advance
public function store(Request $request, AppMailer $mailer)
{
$validatedData=$request->validate([
.......
........
]);
$tracking_model = new Tracking;
$result = $tracking_model->add($request->all());
if ($result === true) {
return redirect('posts')->with('success', 'Created Successfully');
}
else{
$err_msgs = $result;
//what to do here ???????
// return redirect('posts/create')->with('error', $err_msgs);
}
}
try this
in the controller
return redirect('posts/create')->withInput()->withErrors($err_msgs);
and in view .blade
#if ($errors->any())
#foreach ($errors as $error)
...
#endforeach
#else
No tags
#endif

Laravel passing data to page

I am trying to pass data to Controller of Laravel. here is how I do that :
in PagesController::
class PagesController extends Controller
{
public function contact(){
$data="some random ";
return view('contact',compact("data"));
}
}
now in contact.blade.php :
contact pages {{ $data }}
and it s hows
Whoops, looks like something went wrong.
What may be a problam?
try this
public function contact()
{
$data = 'some random';
return View('contact')->with('data' , $data );
}
make sure that the view works fine (if its inside a folder use return View('foldername.contact')
make sure that your view name is contact.blade.php (check uppercase letters)
and inside your view
this is my {{ $data }}

Handling non objects

I might have a controller function like so
public function index()
{
$poll = DB::table('poll')->whereNull('deleted_at')->orderBy('id', 'desc')->first();
$question = DB::table('poll_question')->whereNull('deleted_at')->where('poll_id', $poll->id)->first();
$answers = DB::table('poll_answer')->whereNull('deleted_at')->where('question_id', $question->id)->orderBy('id')->get();
return view('index', compact('poll', 'question', 'answers'));
}
This is fine if the three collections I am obtaining contain data. If they dont and I try to visit the index page, I get
ErrorException in PollResponseController.php line 20: Trying to get property of non-object
So what is the best way to handle non-object's? To bypass this, I could do
public function index()
{
$poll = DB::table('poll')->whereNull('deleted_at')->orderBy('id', 'desc')->first();
if($poll) {
$question = DB::table('poll_question')->whereNull('deleted_at')->where('poll_id', $poll->id)->first();
if($question) {
$answers = DB::table('poll_answer')->whereNull('deleted_at')->where('question_id', $question->id)->orderBy('id')->get();
return view('index', compact('poll', 'question', 'answers'));
}
}
return view('error');
}
But is that not a bit exessive? I was just wondering if there was a better approach to handling this?
Thanks
You can use simple if($question) clause or if(is_null($question)).
$question = DB::table('poll_question')->whereNull('deleted_at')->where('poll_id', $poll->id)->first();
if($question){
// The object is not empty, so I'll use it
}else{
// The object is empty
}
In a blade template it will look like #if($question) and #if(is_null($question)) respectively.
#if($question)
{{ $question->property }}
#endif
In most cases you should just bypass all variables in a template and then check each of them with #if clauses.

Resources