Routing Laravel namepsace issue - php

When I remove the inital use Illuminate\Http\Request and add use App\Item instead in the Controller file, the items/create route responds with a 404. How can I still use the App\Item namespace and get to the items/create route? I've tried adding both, but does not work.
web.php
Route::get('items', 'ItemsController#index');
Route::get('items/{item}', 'ItemsController#show');
Route::get('items/create', 'ItemsController#create');
ItemsController.php
<?php
namespace App\Http\Controllers;
use App\Item;
class ItemsController extends Controller
{
public function index(){
$items = Item::all();
return view('items.index', ['items' => $items]);
}
public function show(Item $item){
return $item->body;
}
public function create(){
return view('items.create');
}
}
Item.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Item extends Model
{
//
}

The problem is that laravel tries to match the routes in the order they are declared and the items/{item} route will match all routes starting with items/, including items/create. And because of the route model binding, Laravel tries to load an Item with ID create which obviously doesn't exist, so it throws a 404 error.
Route model binding in the docs:
Since the $user variable is type-hinted as the App\User Eloquent model
and the variable name matches the {user} URI segment, Laravel will
automatically inject the model instance that has an ID matching the
corresponding value from the request URI. If a matching model instance
is not found in the database, a 404 HTTP response will automatically
be generated.
To fix it simply change the order of your routes and put items/{item} after all other item/* routes:
Route::get('items', 'ItemsController#index');
Route::get('items/create', 'ItemsController#create');
Route::get('items/{item}', 'ItemsController#show');

Can you try this, please.
<?php
namespace App\Http\Controllers;
use App\Item;
class ItemsController extends Controller
{
public function index(){
$items = Item::all();
return view('items.index', ['items' => $items]);
}
public function show($id){
$item= Item::find($id);
return $item->body;
}
public function create(){
return view('items.create');
}
}

Related

inheritance i laravel :Class name must be a valid object or a string

this is my parent class which is a user class that has the main crud operations
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Repositories\UserRepository; //<----------- Here
class UserController extends Controller
{
protected $model;
public function index()
{
$users = $this->model::all();
return view('users.index', compact('users'));
}
}
this is my child class which is one of my user roles , it have the same crud operation but it need some more functinality
<?php
namespace App\Http\Controllers;
use App\Models\Teacher;
use App\Http\Controllers\UserController;
class TeacherController extends UserController
{
public function __construct()
{
$this->model = Teacher::class;
}
}
when I try to access the route i get this error : Class name must be a valid object or a string
at :
$users = $this->model::all();
Well, it seems my Laravel project used old cached routes. Just run
php artisan route:clear
from time to time before debugging anything.

Laravel method show in controller resource return null

i just starting to learn Laravel and trying to use controller resource but somehow the show method just return null
Model
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class barang extends Model
{
use HasFactory;
protected $guarded = ['id'];
}
Controller
use App\Models\Barang;
use Illuminate\Http\Request;
class DashboardBarangController extends Controller
{
public function show(barang $barang)
{
return $barang
}
}
Route
Route::resource('/dashboard/daftar-barang', DashboardBarangController::class)
->middleware(['auth']);
Blade
test
This is called Route Model Binding - implicit binding.
If in your resource route URL used with a dash(-) '/dashboard/daftar-barang/' your controller bound variable must be like $daftarBarang
simple run php artisan route:list to list out all routes.
So in your controller view function must be
public function show(barang $daftarBarang){
return $daftarBarang;
}

show(Model $model) is not working in Laravel 7

I have created a ModelController. In the show(ModelName $model), I have defined the method:
`
show(ModelName $model){
return response()->json(['data'=>$model]);
}
`, but it is not working as expected. It should return the model with its attributes, but it is returning an empty array.
My route is:
Route::resource('model','ModelController');
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
class ModelName extends Model
{
use Notifiable,SoftDeletes;
protected $fillable = [
'name',
];
}
All the other methods are returning expected values. Just the show method is not working properly. I tried using
show($id){
$model = ModelName::findOrFail($id)
return response()->json(['data'=>$model]);
}
This works perfectly, but I cannot use show(Model $model) this type of function call. I can retrieve user data by the same kind of method.
I can not figure out what the problem is. Does anyone have a solution?
check your route list by cmd php artisan route:list --name=Model
match case in uri, is that same as your (Model $model),
$model should be same as {model} in uri (casesenstive)
Try specifying your model in ModelController like so:
class ModelController extends Controller
{
protect $model = ModelName::class;
}

UsersController `User::all()` working but `show` returning `null`

I want to fetch user based on id but it's returning null but User::all() is working correctly.
index and show methods in UsersController :-
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use DB;
class UsersController extends Controller
{
public function __construct()
{
$this->middleware('auth',['except'=>['index','show']]);
}
public function index()
{
$users=User::all();
return view('dev.index')->with('users',$users);
}
public function show(User $user)
{
return view('dev.show')->with('user',$user);
}
}
Route:-
Route::resource('devs','UsersController');
On view I have {{dd($user->name)}} and it's returning null on url public/devs/{dev}.
but working fine on index on url public/devs
This is because you are defining your base route like this:
Route::resource('devs', 'UserController');
This means that laravel will format the show method as follows:
Route::get('devs/{dev}', 'UserController#show');
Laravel will try to solve this dependency doind Implicit Model Binding and given that {dev} doesn't match any of your defined model classes, it will indeed return null.
So to solve it, define this match explicitly doing Explicit Binding. To accomplish this, go to your:
App/Providers/RouteServiceProvider.php
public function boot()
{
parent::boot();
Route::model('dev', App\User::class);
}
So now wherever Laravel reads the {dev} route parameter, will match it with the User model.
You don't initialize users for your entire controller.
Each function uses their own variables
First of all, I would reconfigure your route like so:
Route::get('devs', 'UsersController#show')->name('showUsers')
In your function show I would do the following
public static function show(){
$id = 1;
$users = User::where('id', $id')
return view('dev.show', compact('users'));
}

Laravel 5 - How do I return a oneToMany relationship?

I'm new to Laravel, and using Laravel 5 i'm having trouble returning an array from my database.
I have several "acts", and each act has many "banners". Whenever I try to get output from my array of banners ( $act->banners->count() ), i find it throws an error because it is null.
Here is the code:
routes.php:
Route::model('banners', 'Banner');
Route::model('acts', 'Act');
// Controller routes
Route::resource('acts', 'sf_ActController');
Route::resource('acts.banners', 'sf_BannerController');
Route::bind('banners', function($value, $route) {
return App\Banner::whereact_id($value)->first();
});
Route::bind('acts', function($value, $route) {
return App\Act::whereact_id($value)->first();
});
Act.php (model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Act extends Model
{
protected $table = 'sf_act';
protected $primaryKey = 'act_id';
public function act() {
return $this->hasMany('Banner');
}
}
Banner.php (model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Banner extends Model
{
protected $table = 'sf_banner';
protected $primaryKey = 'banner_id';
public function banner() {
return $this->belongsTo('Act' , 'act_id' , 'act_id');
}
}
sf_ActController.php (controller)
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Act;
use App\Banner;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Input;
use Redirect;
class sf_ActController extends Controller
{
public function show(Act $act)
{
//pass object to correct view
return view('pages.acts.show' , compact('act'))->with('banner', Banner::find($act));
}
acts/show.blade.php (view)
<!-- /resources/views/acts/show.blade.php -->
#extends('app')
#section('content')
<h2>{{ $act->act_title }}</h2>
{{ $act->banners->count() }}
at this point I get the following error:
FatalErrorException in a03036ad81fb4e6d90e9fe5e3da62c65 line 7:
Call to a member function count() on null
Why am I not fetching my banner data!? (The title variable in the h2 tags outputs fine, so the db and everything up until that point is working.)Thanks.
You need to specify the complete "route" to the model in the relationships including the namespace:
public function act() {
return $this->hasMany('App\Banner');
}
And the same on belongsTo:
public function banner() {
return $this->belongsTo('App\Act' , 'act_id' , 'act_id');
}
Could be a good idea to include the name of the foreign kay in the hasMany method.
public function act() {
return $this->hasMany('App\Banner', 'act_id');
}
Also possibly you don't need to include the third parameter in the belongs to.
Hope it helps. Also can share with you a link to learn about Laravel step-by-step: Learn Laravel 5.0 => 5.1
You currently have your hasMany relationship setup like this:
public function act() {
return $this->hasMany('Banner');
}
However in your view your calling this relationship:
$act->banners->count()
Shouldn't it be:
$act->act()->count();

Categories