Passing data from one controller to another through a route Laravel 7 - php

I have setup a system that relies on the routes.php and I have now come across a problem which is that I need to pass a variable to a route which redirects to a controller and receive that variable in the controller. Is this possible. Thanks
Main Controller
return redirect()->route('ROUTENAME')->with("Variable", Array);// Variable has to come from here
web.php
Route::get('ROUTE', "FUNCTION")->name('ROUTENAME');//Need to receive the array here and pass it on
RecieveFunction
$Variable;//This was passed from Main Controller and forwarded from the route

You can use session()->get('Variable'); in the RecieveFunction

You could do this to receive data:
use Illuminate\Http\Request;
Route::get('ROUTE', static function(Request $request){
...
$variable = $request->session()->get('Variable'));
# Delete the data if you don't to keep it in session
$request->session()->forget('Variable');
...
} )->name('ROUTENAME');
OR if you want to pass it to Controller
use App\Http\Controllers\ReceivingController;
Route::get('ROUTE', [ReceivingController::class, 'function_name'] )->name('ROUTENAME');
# ReceivingController
public function function_name(Request $request)
{
...
$variable = $request->session()->get('Variable'));
# Delete the data if you don't to keep it in session
$request->session()->forget('Variable');
...
}

Related

Get the multiple query ? parameters passed in laravel url

AM using angular4 with laravel and am trying to append query parameters and read them in laravel as follows
My http request is get
The url after adding parameters look like
http://localhost:8000/user-management/users?global_filter=12
?paginator=10?page=0?sortfield=username|asc
Now in my laravel routes i have
Route::group(['prefix'=> 'user-management','middleware'=>['auth:api']], function() {
Route::resource('users', "UsersController");
});
Now in my usersController i have
class UsersController extends Controller{
public function index(Request $request)
{
return $request->all();
}
Now the above returns
global_filter:"null?paginator=10?page=0..."
The problem comes when i want to access the paginator value which is null as above.
How do i go about this so that i can be able to retrieve attached values of globalfilter, paginator and sortfield.
I still would wish to continue using the route resource
According to the Url in your question http://localhost:8000/user-management/users?global_filter=12?paginator=10?page=0sortfield=username|ascz it seems you wrongly add ? twice and it caouse the first queryString eliminated and just second part detected, I suggest you use & instead of the second ?.

How can I redirect a Laravel route without a parameter to a controller method with a default parameter?

Assume the following routes in a Laravel 5.5 API:
// custom routes for THIS user (the user making the request)
Route::get('/user', 'UserController#show');
Route::get('/user/edit', 'UserController#edit');
// register CRUDdy resource routes for users
Route::resource('users', 'UserController');
Let's use edit as the example:
public function edit(User $user)
{
...
}
As you can see, the edit route contains a type-hinted $user parameter. This works just fine for the users/13/edit route, as expected. However, I'd to configure the route /user/edit to pass along the $request->user() user object to the function. I don't want to check for the user object in the actual edit method as that could interfere with other validation (for instance, I don't want to default to the current user if someone passes a non-existent user ID, I want to return an error in that case).
In short: how can I register a route to first create a parameter, then pass it to the given controller method? My first thought was to use a closure:
Route::get('/user/edit', function(Request $request){
$user = $request->user();
});
But once inside the closure, I'm not certain how to then carry the request forward to the appropriate controller method.
Instead of a closure, you could make a new controller method that calls edit with the current user.
Let's say your route is this:
Route::get('/user/edit', 'UserController#editSelf');
Then in your controller:
public function editSelf(Request $request)
{
$this->edit($request->user());
}

Bind posted data to a model in Laravel 5.4

I have seen other topics regarding this issue, didn't work out.
So in Laravel 5.4 Route Model Binding, we can bind a route to a model like:
define the route in web.php:
web.php:
Route::get('/users/{user}', UsersController#show);
UsersController#show:
public function show(User $user){
// now we already have access to $user because of route model binding
// so we don't need to use User::find($user), we just return it:
return view(users.show, compact('user'));
}
The above code will work just fine, so in our controller we can return the $user without finding the user, we already have it.
but imagine this:
web.php:
Route::patch('/users/archive', UsersController#archive);
EDITED: now the above line makes a patch route and we don't have {user} in the route url, the user id is being posted via the form.
UsersController#archive:
public function archive(Request $request, User $user){
// how can I access the $user here without using User::find($user);
// I get to this action via a form which is posting `user` as a value like `5`
dd($request->user); // this now echo `5`
// I can do:
// $user = User::find($request->user);
// and it works, but is there a way to not repeat it every time in every action
}
What I have tried:
in RouteServiceProvider::boot() I have:
Route::model('user', 'App\User');
The above is what i have found in Google, but not working.
I would appreciate any kind of help.
EDIT:
It seems it's not called Route Model Binding anymore since we don't have the {user} in the route and that's because my code is not working, the user variable is being posted to the controller and it's only accessible via $request->user.
this is route model binding:
Route::patch('users/{user}/archive', UsersController#archive);
this is not:
Route::patch('users/archive', UsersController#archive);
since we don't have {user} and it's being posted via the form and could be accessed only via $request->user.
(please correct me if I am wrong about the definition of route model binding)
SO:
what I want to achieve in a nutshell: in every request being sent to my UsersController, if I am sending user variable as a post variable, it must be bounded to User::findOrFail($request->user) and then $user must be available in my controller actions.
I want to achieve this because in every action I am repeating myself doing User::findOrFail($request->user) and I don't want to do that, so I want to check in every request if I have a variable name like a model name, they should be bounded.
There's no need to bind explicitly to the User class, so Route::model('user', 'App\User'); should be removed; type-hinting should be enough instead.
public function archive(Request $request, User $user) { ... }
should be working, just make sure you are importing the right User class at the top of the file (use App\User;).
Then the model is in your $user variable (method argument), try dd($user).
It's clear now that since the {user} variable is not in the URI, this is not a route model binding issue. You just want the User instance injected as a parameter based on the contents of the request.
$this->app->bind(User::class, function () {
$user_id = request('user') ?: request()->route('user');
return User::findOrFail($user_id);
});
You could add that to the register method in the AppServiceProvider (or any other registered provider) to have the model injected. I leave it to you to generalize this to other model classes.
You don't even need (Request $request) in your controller.
If you correctly imported User class, as alepeino said, you can access all user values from Model with this syntax $user-><value> for example:
public function archive(User $user) {
$userId = $user->id;
}
According to update.
If you use POST request, you can access it's data with such code request()->get('<variable you send as parameter>')
For example:
public function archive() {
$userId = request()->get('user');
$userInfo = User::find($userId);
//Or as you said
$user = User::findOrFail(request()->get('user'));
}
Can you try this;
public function archive(Request $request, $u = User::find($user){
//now variable $u should point to the user with id from url
}

Adding in a variable via route with static route laravel

I want to be able to add a variable to a route that directs to a controller.
The only way I've seen it done is if the route itself is dynamic. However, in my case, I want a static url that will send a static variable to a controller. The reason for which is that there will be two static routes that will use the same controller in a different way via variables.
I am having trouble finding this in the documentation.
All I have found is this
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
I want to do the same but have {comment} and {post} but two variables is sent to the controllers.
Any help would be awesome!
Forexample:
Route::get('posts/{post}/comments/{comment}', ['as'=> 'viewComment', 'uses'=>'PostController#viewComment']);
Controller:
public function viewComment ($post, $comment)
{
dd($post.'/'.$comment);
}

return back() in Laravel without session params

I have this code in a project with Laravel 5:
return back()->with('msg_ok','successfully sent');
The param msg_ok is pushed in Session, but I´m not want use session params, I want pass the msg_ok parameter as variable.
For example I want print this en my blade file:
{{ $msg_ok }}
Laravel back() function will always return data in a Session. Normally you can't return variable with back() function. You have to use view() function for that.
Alternate Solution
You can use keep() function for storing data in session like variable. Which will not be flushed after refresh.
e.g
$request->session()->keep(['username', 'email']);
and then get data with key.
Laravel back() will redirect you back from the form where it is submitted,
and back()->with('msg_ok', 'successfully..');
if you place an item inside back()->with(); it will automatically place the value
inside session.
You can use return redirect()->to('url/path?msg_ok=successfully') add the query string parameter to url to pass it as variable.
and then on the controller where you have been redirected inject the Reqest class to your method
e.g
public function index(Request $request) {
$msg_ok = $request->get('msg_ok', '');
return view('view.blade', compact('msg_ok'));
}
Place the variable string inside the compact to make it accessible to your view.
You can just use Session::get('msg_ok') in your blade file. Or pass the variable to the view explicitly, in controller, like
return view()->make('view', ['msg_ok' => session()->get('msg_ok')]);

Categories