Route model binding not working on Laravel - laravel

I have been trying to solve this issue since two days but no luck. I do have a update method on my ArticleController that is responsible to update the articles on my database:
public function update(Article $articles, ArticleRequest $request){
$article = Article::findOrFail($articles);
$article->update($request->all());
return redirect('articles');
}
Here is my blade file to show those results:
#extends('app')
#section ('content')
<div class="container">
<h1>Edit: {{$article->title}}</h1>
{!!Form::model($article,['method'=>'PATCH', 'action'=>['ArticleController#update', $article->id] ])!!}
#include('pages.partials', ['submitButtonText' => 'Edit Article'])
{!!Form::close()!!}
#include('errors.error')
</div>
#endsection
I get error Article var doesnt exists.

When you set up route-model binding, behind the scenes Laravel retrieves the appropriate model instance for you and passes it into your controller method. In your example, the Article $articles argument represents an instance of the Article model - not just the id. Therefore, the following line is both unnecessary (since you already have the appropriate model instance), and incorrect (since findOrFail expects an integer to be passed to it - not a model instance):
$article = Article::findOrFail($articles);
I would change your controller method to be:
public function update(Article $articles, ArticleRequest $request)
{
$articles->update($request->all());
return redirect('articles');
}
If you still have trouble with that, "die and dump" your $articles variable to ensure you have route-model binding set up correctly.

Related

Why this Implicit Binding is not working? - Laravel

I'm using Laravel 9. I have a problem, i wil appreciate any help.
I Have a Model named Entity, a controller EntityControler, and a FormRequest UpdateEntityRequest.
My API Routes looks like:
Route::apiResource('entities', EntityController::class);
so i have show, create, store, update, delete... routes.
This is muy update method in EntityController (without the code/not important now)
public function update(UpdateEntityRequest $request, Entity $entity)
{
return $entity;
}
the update method works perfect. But I want another update method for only a section and here starts the problem.
This is my new API Routes:
Route::apiResource('entities', EntityController::class);
Route::patch('/entities/{id}/{section}',[EntityController::class, 'updateSection' ]);
And this is the new method in the controller(without code yet):
public function updateSection( UpdateEntityRequest $request,Entity $entity, $section)
{
return $entity;
}
But this last method return [] insted of the Entity and the update method works. WHY?
I change de uri in Postman for update PUT {{baseUrl}}/entities/1 and for updateSection {{baseUrl}}/entities/1/1 .
Why does work in update and not in updateSection?
PD:
This method work, and give the id, and I can create a Entity from this:
public function updateSection( UpdateEntityRequest $request, $entity, $section)
{
return $entity;
}
But this is not what I want. Any idea why this happen?
please make sure your uri segment is same as the variable name in the controller, in your case replace id with entity
Route::patch('/entities/{entity}/{section}',[EntityController::class, 'updateSection' ]);
for more please see documentation
Make the route param name consistent in your route api.php and your function updateSection in EntityController
Route::patch('/entities/{entity}/{section}',[EntityController::class, 'updateSection' ]);
and
public function updateSection( UpdateEntityRequest $request,Entity $entity, $section)
{
return $entity;
}

Laravel missing parameters to update form in controller

So I have a little project, in it, there's the possibility to upload banners images to be shown on the main page. All the stuff related to the DB are already created and the option to create a banner is working, it creates the banner and then stores the image on the DB for use later. Now I'm trying to work on an edit function so I can change the description under the bannners. I have an Edit route in my controller which returns a view where I edit said banner then it calls the update function on the controller. But no matter what I put here, I'm always getting the Missing Required Parameters error once I try to Save the edit and open my controller through the Update function. Here's the code as it is now:
The route definition:
Route::resource('banner', 'BannerController');
The edit function on my controller:
public function edit($id)
{
return view('admin/edit-banners',['id'=>$id]);
}
The update function has not been implemented because I always start with a dd() function to check if everything is working fine:
public function update(Request $request, $id)
{
dd($request);
}
And here's the form line in my edit view that is trying to call the update route:
<form class="card-box" action="{{ route('banner.update',[$banner]) }}">
I also added this at the beginning of the view to store the data from the DB into a variable:
#php
use\App\Banner;
$banner = Banner::where('id','=',$id)->get();
#endphp
The $banner variable contains all the information on the banner being edited, and I can get the new description at the controller with the $request variable, so I honestly don't know what should I put here as parameters, any ideas?
The $banner variable is not a Model instance, it is a Collection.
Adjust your controller to pass this to the view instead of dong the query in the view:
public function edit($id)
{
$banner = Banner::findOrFail($id);
return view('admin.edit-banners', ['banner' => $banner]);
}
You could also use Route Model Binding here instead of doing the query yourself.
Remove that #php block from your view.
The form should be adjusted to use method POST and spoof the method PUT or PATCH (as the update route is a PUT or PATCH route) and you should adjust the call to route:
<form class="card-box" action="{{ route('banner.update', ['banner' => $banner]) }}" method="POST">
#method('PUT')
If you include $id in your function declaration then when you call the route helper it expects you to give it an id parameter. Try with
<form class="card-box" action="{{ route('banner.update',['id' => $id]) }}">
You should be able to retrieve the form data just fine form the $request variable. More info here.
The code below should be the error source. $banner variable then is an array but the update function accept object or id.
#php
use\App\Banner;
$banner = Banner::where('id','=',$id)->get();
#endphp
You should try to replay this code by this one...
#php
use\App\Banner;
$banner = Banner::find($id);
//you should put a dd here to view the contain of $banner if you like
#endphp
Hop it help...

Laravel 5.8 error trying to get the 'id' property of non-object

I'm developing an application with Laravel 5.8. In my application, I have a controller that handles backend articles, and it works. I want to display my user-side information in such a way that a user can click on a link and see the detail of an article. For that, I have created a new controller a with a new namespace for the function show my redirection of navigation in different page does not focus that it is en route or URL with Laravel 5.8. Below is the function.
namespace App\Http\Controllers\Cybernaut;
use App\History;
use App\Http\Controllers\Controller;
class HistoryController extends Controller
{
public function show($id)
{
$history = History::find($id);
return view('show_history', compact('history'));
}
}
At the level of the home page I wanted to have my links like these:
<li><a data-hover="history" href="{{route('history.show',$history→id)}}"><span>history</span></a></li>
Error
ErrorException (E_ERROR) Property [id] does not exist on this
collection instance. (View:
C:\laragon\www\venome\resources\views\layouts\partial\header.blade.php)
And here is the route used for the show function.
Route::group(['namespace'=>'cybernaut'], function (){
Route::get('/history/{slug}','HistoryController#show')->name('history.show');
});
Try after modifying the thing I have these at the route level now.
Route::get('/', 'FrontController#index')->name('index');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/admin/dashboard', 'DashboardController#index')->name('admin.dashboard');
Route::group([], function () {
Route::get('/history', 'HistoryController#index')->name('history.index');
Route::get('/history', 'HistoryController#create')->name('history.create');
Route::get('/history/edit', 'HistoryController#update')->name('history.update');
Route::get('/history', 'HistoryController#destroy')->name('history.destroy');
});
Route::group(['namespace' => 'cybernaut'], function () {
Route::get('/history/{history}', [
'as' => 'show',
'uses' => 'HistoryController#show'
]);
});
At the level of the homepage I wanted to put my link like those here now;
#foreach($history as $history)
<li><a data-hover="history" href="{{url('/history/'.$history->id)}}"><span>history</span></a></li>
#endforeach
I have this error now:
Trying to get property 'id' of non-object (View:
C:\laragon\www\venome\resources\views\layouts\partial\header.blade.php)
I want an internaut to be able to navigate between the pages.
You have a conflict of variables on your homepage.
#foreach($history as $history)
should be
#foreach($histories as $history)
where $histories is filled in in your FrontController.
$histories = History::all();
When actually getting your single history object, I agree with Sapnesh's answer that you best doublecheck whether or not the object actually exists.
The error occurs because find() returns NULL when a model is not found.
find($id) takes an id and returns a single model. If no matching model
exist, it returns null.
findOrFail($id) takes an id and returns a single model. If no matching
model exists, it throws an error.
In your show() method,
Change:
$history = History::find($id);
To:
$history = History::findOrFail($id);

how to access function defined in model to view?

my laravel model funciton :
public function isAdminOrSuperAdmin()
{
return $this->role() == config('custom_config.constants.user_types.SUPER_ADMIN')
|| $this->role() == config('custom_config.constants.user_types.ADMIN');
}
i try to access in view :
#if($user->isAdminOrSuperAdmin())
<a class="btn btn-primary pull-right" style="margin-top:
-10px;margin-bottom: 5px" href="{!! route('admin.users.create') !!}">
Add New
</a>
#endif
but it show error:
Method Illuminate\Database\Eloquent\Collection::isAdminOrSuperAdmin does not exist. (View:/resources/views/admin/users/index.blade.php)
thanks in advance.
Check the error:
Method Illuminate\Database\Eloquent\Collection::isAdminOrSuperAdmin does not exist. (View:/resources/views/admin/users/index.blade.php)
This means, you are trying to call a method of your model on a Collection instance instead of an actual User model instance.
When querying several items from your database, Laravel returns an instance of the Collection class that contains all the resulting model objects.
Maybe you are doing something like this:
public function aCoolFunction()
{
$user = User::where('column', 'value')
->get(); // <-----
return view('my_view')->with('user', $user);
}
The get() method returns a Collection, not a single element.
Try the first() instead:
public function aCoolFunction()
{
$user = User::where('column', 'value')
->first(); // <-----
return view('my_view')->with('user', $user);
}
Now in your view the $user variable will actually hold and instance of your User model user in which the isAdminOrSuperAdmin() method is defined, and not a collection of it.
I don't think this is the best way but you can pass the function to view using your controller :
in your controller :
public function index(User $user)
{
$ModelFunction = $user->yourModelFunction();
return View('test',compact('user','ModelFunction'));
}
And in your View :
{{ $ModelFunction }}
you must call function like this:
#if(is_admin_or_super_admin())

Undefined variable: post (View: E:\xamp\htdocs\lsapp\resources\views\posts\index.blade.php)

I am new to laravel, and getting this error though tried every possible sites and google searches. I even tried previous queries solution from stack overflow, but was unable to solve.
this is my PostController.php:
`public function getData()
{
$post['post']=DB::table('students')->get();
if(count($post)>0){
return view('index',['Post'=>'$post'] );
}
else{
return view('index');
}
}`
this is my controller
This is my index.blade.php:
`#foreach($post as $value)
<tr>
<td>{{$value->id}}</td>
<td>{{$value->name}}</td>
<td>{{$value->address}}</td>
<td>{{$value->number}}</td>
<td><a href="" ><button>Edit</button></a> <a href="" >
<button>Delete</button></a></td>
</tr>`
This is my blade:
Route::get('/index','PostController#getData');
this is my route
please help in this queries, i am having a lots of problem
There are a number of problems with your code. I would recommend you go through laravel documentation and first 2 PSRs
As error clearly states that there is not a variable $post in the view. In else you are not sending the $post variable and in if you are sending the $post variable with a capital P but you are accessing it using lower case p in your view. So the variable is not available in any case in the view that's why it is showing that error.
PHP variables are case sensitive and do not use the quotes around php variable (the one with $ sign) in the parameters that you are passing to the view.
return view('index',['Post'=>'$post'] );
Above statement should be written as
return view('index',['post'=>$post] );
also update your controller method and I don't know why are you using associative array ($post['post']).
public function getData()
{
$post = DB::table('students')->get();
return view('index',['post'=>'$post'] );
}
I identified this problem. You send the posts variable in the index function.
public function index(){
$posts = Post::all();
return view('posts.index',compact('posts'));
}
But most likely you get this error when you want to create a new post, so here the store function is executed and the index function is not executed in the controller, because the store function is responsible for storing form information. Then you edit this function as follows.
public function store(Request $request) {
$post = new Post();
$post->title = $request->input("title");
$post->description = $request->input("description");
$post->save();
$posts = Post::all(); //Send posts in compact
return view("posts.index", compact($posts));
}
Excuse me for the typing problem, I am a Persian speaker ❤

Resources