Can I remove the following line of code
use Illuminate\Http\Request;
form laravel Controller? Is this a good practice?
For example, my HomeController:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$totals = [
'customers' => \App\Customer::count(),
'jobs' => \App\Job::count(),
'invoices' => \App\Invoice::count(),
];
$data = [
'page_title' => 'Dashboard',
'totals' => $totals
];
return view('home', $data);
}
}
Here I don't need the "Request", because none of the functions doesn't use that parameter.
To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your controller method. The incoming request instance will automatically be injected by the service container.
So if you don't want To obtain an instance of the current HTTP request then remove it.
Yes if you are using just select data query you can go ahead and remove this line. It's need where you will use any get or post form in your class function.
Related
I am new to Laravel and I am trying to edit and delete user transactions, but I am stuck with this error:
The update_transaction method is not supported for route POST.
Supported methods: GET, HEAD.
This is my EditTransferController:
namespace App\Http\Controllers;
use App\Models\transfer;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\Support\Str;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class EditTransferController extends Controller
{
public function update_transaction(Request $request)
{
$id = $request->id;
$transfer = Transfer::find($id);
return view('Transfers_profile', ['transfer' => $transfer]);
}
public function delete_transaction(Request $request)
{
$transfer = $request->id;
Transfer::find($transfer)->delete();
return view('AllTransfers');
}
}
And this is routes/web.php:
Route::get('/update_transaction', function (Request $request) {
$transfer = Transfer::find($request->id);
return view('update_transaction', ['transfer' => $transfer]);
})->name('update_transaction');
Route::PUT('/transaction_profile', [EditTransferController::class, 'update_transaction'])->name('post_transaction_profile');
Route::post('/transaction_delete', [EditTransferController::class, 'delete_transaction'])->name('delete_transaction_profile');
It looks like there are a few issues with the code you've provided:
In the routes/web.php file, the update_transaction route is defined
as a GET request, but the controller method that should handle the
request is expecting a PUT request. To fix this, you should change
the route definition to:
Route::get('/update_transaction/{id}', [EditTransferController::class, 'update_transaction'])->name('update_transaction');
In the EditTransferController, the update_transaction method expects
the id to be passed in the request, but you are not passing it from
the route. To fix this, you should pass the id when calling the
route, like this:
return redirect()->route('update_transaction', ['id' => $id]);
The delete_transaction route is defined as a POST request, but the
controller method that should handle the request is expecting a
DELETE request. To fix this, you should change the route definition
to:
Route::delete('/transaction_delete/{id}', [EditTransferController::class, 'delete_transaction'])->name('delete_transaction_profile');
In the EditTransferController, the delete_transaction method expects
the id to be passed in the request, but you are not passing it from
the route. To fix this, you should pass the id when calling the
route, like this:
return redirect()->route('delete_transaction_profile', ['id' => $id]);
In the update_transaction method, you are using Transfer model but
it is defined as transfer in the use statement. So you should change
the Transfer to transfer
In the delete_transaction method, you are trying to delete a record
by passing $request->id but it should be $request->transfer.
You should change the above mentioned issues in your code, it should work fine.
I have many routes, and for a single page (my homepage) I need to sample almost all of my models. I do it like that:
use App\Models\Aa;
use App\Models\Bb;
use App\Models\Cc;
// and so on ...
Route::get('/', function () {
$data_for_view = [
'aa' => Aa::where('show', true)->inRandomOrder()->limit(4)->get(),
'bb' => Bb::where('published', true)->limit(4)->get(),
'cc' => Cc::where('published', true)->limit(4)->get()
// ... and so on
// ...
];
return view('welcome', $data_for_view);
});
However, this is the only route that uses so many models. so my questions is: is there a better way to achieve that goal?
is it a standard practice?
In the beginning you should use some controller for that and wrap your all logic inside method
For example:
in web.php route file add this:
use App\Http\Controllers\SomeController;
// SomeController
Route::get('/', [SomeController::class, 'index']);
In SomeController
<?php
namespace App\Http\Controllers;
use App\Models\Aa;
use App\Models\Bb;
use App\Models\Cc;
class SomeController extends Controller
{
public function index()
{
$data_for_view = [
'aa' => Aa::where('show', true)->inRandomOrder()->limit(4)->get(),
'bb' => Bb::where('published', true)->limit(4)->get(),
'cc' => Cc::where('published', true)->limit(4)->get()
// ... and so on
// ...
];
return view('welcome',compact('data_for_view'));
}
}
You can use artisan command for creating controller.
php artisan make:controller SomeController
I'm having problems with and invoke type controller.
After I create the controller with php artisan make:controller -i and add the route, when go to the route it tells me that the Invoke function doesn't exist.
Here is the route I'm using:
Route::get('/portfolio','PortfolioController');
And here is the code of the controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PortfolioController extends Controller
{
public function __invoke(Request $request)
{
/** #var array $portafolio */
$portafolio = [
["title" => "Proyecto #1"],
["title" => "Proyecto #2"],
["title" => "Proyecto #3"],
["title" => "Proyecto #4"],
];
return view("portfolio", compact("portafolio"));
}
}
I don't really get why this error occurs, because the invoke function is clearly there, so if anyone knows what could be the problem I will be really grateful.
I'm using the last version of Laravel.
You need to use the fully qualified class name as in the documentation:
use App\Http\Controllers\PortfolioController;
Route::get('/portfolio', PortfolioController::class);
Hello I'm trying to create a code generator to invite a user from input email, I want to save on the database the user id who send the invite, the code, and the email who is going to recive the invite, but I can't get the id of my auth user doing $request->user('id') (not working) also I know there is other method to do this easier than using DB::table something like
$request->user()->invites()->create... my controller looks like
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class invitacionController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
return view('administrar');
}
public function invitacion(Request $request)
{
$this->validate($request, [
'email' => 'required|email|max:255|unique:invites',
]);
/*$request->user()->invites()->create([
'code' => str_random(40),
]);*/
DB::table('invites')->insert([
['usuId' => $request->user('id'), 'code' => str_random(40), 'email' => $request->input('email')],
]);
return redirect('/administrar');
}
}
If the relationship is properly configured, the first (commented) method should be working.
As for the second method, I think you are adding extra brackets:
DB::table('invites')->insert([
'usuId' => $request->user()->id, // <---
'code' => str_random(40),
'email' => $request->input('email')
]);
That hasMany method can take additional parameters. By default it expects the column to be named user_id, but you called it usuId. The documentation gives this example:
return $this->hasMany('App\Comment', 'foreign_key');
So I think you should do
public function invites()
{
return $this->hasMany(Invite::class, 'usuId');
}
I have a function in my controller. The problem is I must use two Requests at the same time but only one of them can be used in a controller.
Illuminate\Support\Facades\Request
Illuminate\Http\Request
Code:
public function func(Request $req) {
if (Request::isMethod('post')) {
$this->validate($req, [
'username' => 'required|string'
]);
}
}
What is the solution?
If you wanted to use both of them, you can alias them as below:
use Illuminate\Http\Request as RequestNew;
use Illuminate\Support\Facades\Request as RequestOld;
And then you can reference the alias in your code.
eg: RequestNew::isMethod('post')