Laravel 8 Find Method result 404 Not Found - laravel

I just start learning Laravel 8, In my learning project I am using find($id) Method but it ended with 404 Not Found. In my database id is the primary key.
Here are the code I wrote
<td>
Detail
Update
Delete
</td>
For Controller :
public function show($id)
{
$detail = Member::find($id);
return response()->json($detail);
}
Route :
Route::get('/detail/id', [MemberController::class, 'show']);
Please help me, what is wrong with my code?

You are missing curly brackets {id} in the route definition
Route::get('/detail/{id}', [MemberController::class, 'show']);
public function show($id)
{
return Member::findOrFail($id);
}
https://laravel.com/docs/8.x/routing#route-parameters
You can also use route model binding
In your case it will be
Route::get('/detail/{member}', [MemberController::class, 'show']);
public function show(Member $member)
{
return $member;
}
https://laravel.com/docs/8.x/routing#route-model-binding

Related

Attempt to read property "title" on null - Laravel

when I enter the detail page in Laravel, it gives an error. I don't understand where the error is coming from. My codes are as follows.
where is the problem? actually it says it's empty, but it needs to pull data from $blog on controller side.
Controller:
public function show($id)
{
$blog = Blog::where('id',$id)->first();
return view('front.detail',compact('blog'));
}
routes/web.php:
Route::prefix('{lang?}')->middleware('locale')->group(function() {
Route::get('/', [MainController::class, 'index'])->name('home');
Route::get('/about', [MainController::class, 'about'])->name('about');
Route::resource('/blogs', MainController::class)->only([ 'show']);
});
detail.blade.php:
<li>
<h2>{{$blog->title}}</h2>
<p>{!! $blog->text !!}</p>
</li>
If you want to get a model by the main column you use find not where and the column:
public function show($id)
{
$blog = Blog::find($id);
return view('front.detail',compact('blog'));
}
Then, find can return the Model (hence an object) or null, so in your case it is not finding the model by ID.
What you should use is findOrFail so it throws an exception if it did not find the model:
public function show($id)
{
$blog = Blog::findOrFail($id);
return view('front.detail',compact('blog'));
}
Then you can continue debugging why it is not found
Doesn't appear you are passing the blog ID in with your URL:
Route::resource('/blogs', MainController::class)->only([ 'show']);
Try changing your route to this:
Route::resource('/blogs/{id}', MainController::class)->only([ 'show']);
Your URL should be something like (where 5 is the blog ID):
http://yourdomain.com/blogs/5
You could also use binding:
// Route
Route::get('/blogs/{blog}', [MainController::class, 'show']);
public function show(Blog $blog)
{
return view('front.detail', ['blog' => $blog]);
}
More info can be found here:
Route model binding

Laravel authorization policy not working on Show page

I have a laravel app using Policies to assign roles and permissions, i cant seem to access the show page and im not sure what im doing wrong?
If i set return true it still shows a 403 error as well, so im unsure where im going wrong here. The index page is accessable but the show page is not?
UserPolicy
public function viewAny(User $user)
{
if ($user->isSuperAdmin() || $user->hasPermissionTo(44, 'web')) {
return true;
}
return false;
}
public function view(User $user, User $model)
{
if ($user->isSuperAdmin() || $user->hasPermissionTo(44, 'web')) {
return true;
}
return false;
}
UserController
public function __construct()
{
$this->authorizeResource(User::class, 'user');
}
public function index()
{
$page_title = 'Users';
$page_description = 'User Profiles';
$users = User::all();
return view('pages.users.users.index', compact('page_title', 'page_description', 'users'));
}
public function create()
{
//
}
public function store(Request $request)
{
//
}
public function show($id)
{
$user = User::findOrFail($id);
$user_roles = $user->getRoleNames()->toArray();
return view('pages.users.users.show', compact('user', 'user_roles'));
}
Base on Authorize Resource and Resource Controller documentation.
You should run php artisan make:policy UserPolicy --model=User. This allows the policy to navigate within the model.
When you use the authorizeResource() function you should implement your condition in the middleware like:
// For Index
Route::get('/users', [UserController::class, 'index'])->middleware('can:viewAny,user');
// For View
Route::get('/users/{user}', [UserController::class, 'view'])->middleware('can:view,user');
or you can also use one policy for both view and index on your controller.
I had an issue with authorizeResource function.
I stuck on failed auth policy error:
This action is unauthorized.
The problem was that I named controller resource/request param with different name than its model class name.
F. ex. my model class name is Acknowledge , but I named param as timelineAcknowledge
Laravel writes in its documentation that
The authorizeResource method accepts the model's class name as its first argument, and the name of the route / request parameter that will contain the model's ID as its second argument
So the second argument had to be request parameter name.
// Here request param name is timelineAcknowledge
public function show(Acknowledge $timelineAcknowledge)
{
return $timelineAcknowledge->toArray();
}
// So I used this naming here also
public function __construct()
{
$this->authorizeResource(Acknowledge::class, 'timelineAcknowledge');
}
Solution was to name request param to the same name as its model class name.
Fixed code example
// I changed param name to the same as its model name
public function show(Acknowledge $acknowledge)
{
return $acknowledge->toArray();
}
// Changed here also
public function __construct()
{
$this->authorizeResource(Acknowledge::class, 'acknowledge');
}
I looked over Laravel policy auth code and I saw that the code actually expects the name to be as the model class name, but I couldn't find it anywhere mentioned in Laravel docs.
Of course in most of the cases request param name is the same as model class name, but I had a different case.
Hope it might help for someone.

How can I redirect from a controller with a value to another controller in laravel?

OrderController.php
if (request('payment_method') == 'online') {
return redirect(route('payments.pay', $order->id));
}
web.php
Route::POST('/pay/{orderId}', 'PublicSslCommerzPaymentController#index')->name('payments.pay');
PublicSslCommerzPaymentController.php
session_start();
class PublicSslCommerzPaymentController extends Controller
{
public function index(Request $request, $ordId)
{
//code...
}
}
Here in index function I need the order id from `OrderController.
But the Error I am getting
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
if you want to redirect to named route you can use this:
return redirect()->route('payments.pay', ['orderId' => $order->id]);
if you want generate redirect to controller action you can try this:
return redirect()->action(
'PublicSslCommerzPaymentController#index', ['ordId' => $order->id]]
);
Just change in your web.php from POST method to GET method
Something like this
Route::GET('/pay/{orderId}', 'PublicSslCommerzPaymentController#index')->name('payments.pay');

How to remove ID in URL in Laravel return

Laravel 5.4, Everything works fine but one thing is bugging me,
When I edit my Data and submit and use return view('role.index');
The URL returns this :8000/role/1, it returns a extra ID which is I don't know where it came from here is my code:-
public function edit(Role $role)
{
return view('role.edit')->with('details', $role);
}
public function update(Request $request, Role $role)
{
$user=auth()->user();
$role->role=$request->get('role');;
$role->updated_by=$user->id;
$role->save();
return view('role.index');
}
i understood it wrong but the reason that it happens because the route of the update is a "PUT request with the id" -> http://yourwebsite/role/1
you are returning a view inside this route you are still in the Role controller and update method.
The solution
instead of returning a view just
return back();
at the last of the update method

Laravel 5 ModelNotFoundException in Builder.php for Routing

I have a Model Class with name Article.php
and use below rout:
Route::get('articles/create','ArticlesController#create');
when input in browser http://localhost:8000/articles/create
i see this error :
ModelNotFoundException in Builder.php line 125: No query results for model [App\Article].
but when i user below every think is ok:(article insted articles)
Route::get('article/create','ArticlesController#create');
this is my controller :
class ArticlesController extends Controller {
public function index()
{
$articles = Article::all();
return view('articles.index',compact('articles'));
}
public function show($id)
{
$article = Article::findOrFail($id);
return view('articles.show',compact('article'));
}
public function create()
{
return view('articles.create');
}
}
what happened really ?!!!
The problem with your code is that in your routes.php your route priority is like this :
Route::get('articles/{id}','ArticlesController#show');
Route::get('articles/create','ArticlesController#create');
and when you go to http://localhost:8000/articles/create in your browser laravel catches create as a variable with {id} request in articles/{id} before articles/create gets an opportunity to resolve the route. To solve your problem you must consider the route priority and make the following changes to your route.php file :
Route::get('articles/create','ArticlesController#create');
Route::get('articles/{id}/edit','ArticlesController#show');
Route::get('articles/{id}','ArticlesController#show');
But if you have a bunch of these in your routes.php file you should really consider using this instead:
Route::resource('articles', 'ArticlesController');
This single line will take care of all 4 get routes (index, create, edit, show) as well as all three post/put/delete routes of (store, update, delete).
But to each their own.
You should include your controller code.
Most likely there's some code there that tries a findOrFail() on the Eloquent model, triggering this error.

Resources