laravel5 generate routes key - php

i use laravel 5.2 now.
i have these codes in my routes.php file:
Route::(['dashboard'=>'DashboardArticelController',]);
and laravel generates some router for my app :
GET /dashboard/my-articles App\Http\Controllers\DashboardArticelController#getMyArticles
here is a method in my controller:
public function getMyArticles()
{
//$articels = Auth::user()->articals()->latest('published_at')->get();
//dd(Auth::user()->articals()->latest('published_at')->simplePaginate(3));
$articels = Auth::user()->articals()->latest('published_at')->Paginate(5);
return view('dashboard.view.dashboardArticelEdit',compact('articels'));
}
i wonder how the laravel5 generates this route ,i can not found the method can generates the route with the method name.

By default, Laravel assumes an Eloquent model should map to URL segments using its id column. But what if you expect it to always map to a slug?
Eloquent implements the Illuminate\Contracts\Routing\UrlRoutable contract, which means every Eloquent object has a getRouteKeyName() method on it that defines which column should be used to look it up from a URL. By default this is set to id, but you can override that on any Eloquent model:
class Test extends Model
{
public function getRouteKeyName()
{
return 'slug';
}
}

Related

How to pass a model instance to all controllers and views based on a route parameter

I am working on a Laravel control panel project where we should be able to toggle from one site to another and get the detail of the site based on the ID passed in the route.
In itself this is quiet easy to do but as I will have several controllers using this technique it means for each controller and each controller instance I will have collect the site instance and it does not look very user friendly due to the many repetitions.
Here is what I have:
Route:
Route::get(
'cp/site/{website}/modules/feeds',
'App\Http\Controllers\Modules_sites\Feeds\FeedController#index'
)->name('module_site.feeds.index');
Model:
class Website extends Model
{
use HasFactory;
protected $primaryKey ='site_id';
}
The database is simple with an id (site_id) and name
Controller:
public function index(Website $website)
{
dd($website -> name);
}
The above is working fine but I am going to end with dozens of methods across multiple controllers doing the same thing, and what if changes are required.
I have looked at the ID of using the AppServiceProvider to create the Website instance and then pass it to the controllers and views but I can't do this as the route is not defined at this stage and I only seem to be able to pass this to the view.
Essentially, I am looking to create something similar to the auth()->user() method that is available from controllers and routes without the needs to pass it to each controller.
Is this possible?
Perhaps you could use middleware to set this value? Something like this to put it in the session globally:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckWebsite
{
public function handle(Request $request, Closure $next): mixed
{
$request->session()->put("website", $request->route("website"));
return $next($request);
}
}
Or this on a per-controller basis:
<?php
namespace App\Http\Controllers\Modules_sites\Feeds;
use App\Http\Controllers\Controller;
use Closure;
use Illuminate\Http\Request;
class FeedController extends Controller
{
public function __construct()
{
$this->middleware(function (Request $request, Closure $next) {
$this->website = $request->route("website");
return $next($request);
});
}
public function index()
{
dd($this->website->name);
}
}
Also worth mentioning that routes are not defined like that in Laravel 8 any longer. It should look like this:
Route::get(
'cp/site/{website}/modules/feeds',
[FeedController::class, 'index']
)->name('module_site.feeds.index');
With an appropriate import for the controller class.
as you primary key is not id so it will not work automatically you need to tell laravel to search by column name
code will be
Route::get('cp/site/{website:site_id}/modules/feeds', 'App\Http\Controllers\Modules_sites\Feeds\FeedController#index')->name('module_site.feeds.index');
you need to use {website:site_id}
ref link https://laravel.com/docs/8.x/routing#customizing-the-default-key-name

Call a Model method using Laravel Relationship

I'm currently trying to use Laravel Relationships to access my achievements Model using User model, I use this relationship code:
public function achievements()
{
return $this->hasMany('App\Models\User\Achievement');
}
I can easily make some eloquent queries, however I can't access any method that I created there, I can't access this method:
class Achievement extends Model
{
public function achievementsAvailableToClaim(): int
{
// Not an eloquent query
}
}
Using the following code:
Auth::user()->achievements()->achievementsAvailableToClaim();
I believe that I am using this Laravel function in the wrong way, because of that I tried something else without using relationship:
public function achievements()
{
return new \App\Models\User\Achievement;
}
But that would have a performance problem, because would I be creating a new class instance every time I use the achievements function inside user model?
What would be the right way of what I'm trying to do?
it's not working because your eloquent relationship is a hasMany so it return a collection. you can not call the related model function from a collection.
you can var dump it on tinker to understand more what i mean.
You can use laravel scopes.Like local scopes allow you to define common sets of constraints that you may easily re-use throughout your application.
In your case you use this like, Define scope in model:
public function scopeAchievementsAvailableToClaim()
{
return $query->where('achivement_avilable', true);
}
And you can use this like :
Auth::user()->achievements()->achievementsAvailableToClaim();

Why does only some laravel routes return model attributes?

i´m studying laravel but having some doubts..
Controller
namespace App\Http\Controllers;
use App\ItemNfe;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ItensNfeController extends Controller
{
public function edit($id,ItemNfe $itemNfe)
{
//i don´t want to have to make this select below
//$itemNfe = DB::table('itens_nfe')->where('id_itemnfe',$id)->get();
// dd($itemNfe); this dd() returns model attributes on few of my controllers only
return view...
}...
Model: (note i´m not using laravel convention but it´s informed)
namespace App;
use Illuminate\Database\Eloquent\Model;
class ItemNfe extends Model
{
protected $table = 'itens_nfe';
protected $primaryKey = 'id_itemnfe';
protected $fillable = [
'id_itemnfe','fk_venda', 'fk_produto'...
];
public function nfe()
{
return $this->belongsTo('App\Nfe'); //this is one diference among others models, but apparently doesn´t affects when i tested without this code.
}
}
The route i´m using is the same for everyone.. "resource routes"
At the first 2, i have the attributes returning, but not at the last one...
Route::resource('/usuarios', 'UsuariosController');
Route::resource('/nfes', 'NfesController');
Route::resource('/itensnfe', 'ItensNfeController');
The Url used is:
https://localhost/erpoverweb/public/itensnfe/1/edit
If needing more code please tell me... thanks!
If you don't want to manually search the database for the entry, you can use Laravel Container do perform a Dependency Injection. https://laravel.com/docs/7.x/container#introduction
public function edit(ItemNfe $itemNfe)
{
// Returns the model, and you didn't need to manually searched.
// Laravel automaticly injects this for you.
dd($itemNfe);
}
Sounds like you are looking for Route Model Binding (implicit at that). This requires that the route parameter name and the name of the parameter of the method signature for that route match.
public function edit(ItemNfe $itensnfe)
The resource route with resource name 'itensnfe' should make the parameter 'itensnfe'.
If you don't make these match you will just end up with Dependency Injection which would inject a new model instance.
Laravel 7.x Docs - Routing - Route Model Binding - Implicit Binding

Failed Laravel dependency injection in controller method

I have a model called Dbtable which isn't injected when used like this:
public function showEditDbTableForm(Request $request, DbTable $table)
{
}
it only works when I do this:
public function showEditDbTableForm(Request $request, $id)
{
$table = DbTable::find( $id );
}
Same thing happens even when I rename DbTable to DbTble
P.S.: please don't be rude with me as I'm new to Laravel framework
For Implicit Route Model Binding you need to make sure the parameter in the method signature has the same name as the route parameter you want to bind.
Route::get('widgets/{widget}', 'WidgetsController#show');
public function show(Widget $widget)
Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name.
Laravel 5.6 Docs - Routing - Implicit Model Binding
In RouteServiceProvider class add
public function boot()
{
parent::boot();
Route::model('db-table', App\DbTable::class);
// db-table correspond your rout parameter
}
see official documentation https://laravel.com/docs/5.5/routing Explicit Binding section

Route model binding and parent child validation in Laravel

Say I have a route like:
Route::get('users/{user}/posts/{post}', 'PostController#show')
And I've set up Route Model binding for an App\User to {user} and an App\Post to {post}. I've seen I'm able to call whatever existing post for any given user to get contents on the screen. Is there a generic place where I can assign constraints to the bound models?
you can use Route::bind and set a second variable for the function to access the current route and it parameters like this:
class RouteServiceProvider extends ServiceProvider{
public function boot(Router $router)
{
$router->bind('user', function($value) {
return App\User::findOrFail($value);
});
$router->bind('post', function($value, $route) {
return $route->parameter('user')->posts()->findOrFail($value);
});
}
}
You can use $router->bind() to control how a model is fetched:
Route::get('/user/{name}', 'PostController#show');
$router->bind('user', function($value) {
return App\User::where('name', $value)->first();
});
This certainly is a gap in laravel. I made a little package to help.
https://github.com/tarekadam/laravel-orm-binding-validation
Use middleware not validation.
Append the middleware so that binding already ran.
Define the expected relationships in the controller.
See README.md on the package.

Categories