How to send data from laravel route to controller function? - laravel-5

I've a laravel route
Route::get('/find/mobiles','SearchController#byCategory');
I want send values to byCategory method from the route file, something like $category='mobile' or $category = 'television'
I'm unable to find any way to do it.

Route:
Route::get('find/{category}, 'SearchController#byCategory');
Controller:
Public function byCategory($category){
... $category is whatever is passed from the route ...
}

Related

Undefined Variable in Laravel 8 view

I just want to Pass a Variable to the views about page.
This is the controller file
public function about(){
$name ="maneth";
return view::make('about')->with('name', $name);
}
This is the about page
#switch($name)
#case(1)
#break
#case(2)
#break
#default
#endswitch
This is the web file
Route::get('/about',function(){
return view('about',[PagesController::class, 'about']);
});
The Error is $name is undefined
I'm Using Laravel Framework 8.75.0
and PHP 7.3.33
You are using callback in router's file and there you not sent the name variable,
You can bind controller and router file using :
Route::get('/about', [AboutController::class, 'about']);
Your controller action is never being executed as your route definition is returning a view directly.
Change your route so that it calls your controller and action.
Route::get('/about', [AboutController::class, 'about']);
As long as it doesn't require any real logic (database query etc.) you can do it with a closures in your route. Otherwise you have to call the controller from your route. This would look like this:
Route::get('/about', [AboutController::class, 'about' ])->name('about');
And this would be thee closures style:
Route::get('/about',function(){
$name = 'Slim Shaddy';
return view('about', ['name' => $name]);
});

How to use parameter from function to create an URL? Laravel Routing

I'm sending an URL hashed and when i get it i have to show a view on Laravel, so i have those functions on the controller and also some routes:
This are my routes:
Route::post('/sendLink', 'Payment\PaymentController#getPaymentLink');
Route::get('/payment?hash={link}', 'Payment\PaymentController#show');
And this are the functions i have on my controller:
public function getPaymentLink (Request $request){
$budgetId = $request['url.com/payment/payment?hash'];
$link = Crypt::decryptString($budgetId);
Log::debug($link);
//here to the show view i wanna send the link with the id hashed, thats why i dont call show($link)
$view = $this->show($budgetId);
}
public function show($link) {
$config = [
'base_uri' => config('payment.base_uri'), ];
$client = new Client($config);
$banking_entity = $client->get('url')->getBody()->getContents();
$array = json_decode($banking_entity, true);
return view('payment.payment-data')->with('banking_entity', $array);
}
And this is getting a "Page not found" message error.
What i want to to is that when i the client clicks on the link i send him that has this format "url.com/payment/payment?hash=fjadshkfjahsdkfhasdkjha", trigger the getPaymentLink function so i can get de decrypt from that hash and also show him the view .
there is no need to ?hash={link} in get route
it's query params and it will received with $request
like:
$request->hash
// or
$request->get('hash')
You need to define route like this:
Route::get('/payment/{hash}', 'Payment\PaymentController#show');
You can now simply use it in your Controller method like below:
<?php
public function getPaymentLink (Request $request,$hash){
$budgetId = $hash;
// further code goes here
}

How can I route using controller without adding the id in the url?

The url right now is website.com/profile/1/edit but I wanted to just only show website.com/profile
I have tried using the route web.php
Route::resource('profile', 'ProfileController'); and Route::get('profile', 'ProfileController#edit');
You can create some route like that :
Route::get('my_profile','ProfileController#myProfile');
And the function like that :
public function myProfile (){
$user = Auth::User();
if($user){
/*
Your code and redirect
*/
}
else{
return back();
}
}
Don't forget this : use Auth; in above of file
If you want to edit profile of user who is logged in. Try getting the ID from session rather than sending it from the URL. Instead of this, you can also use post request to hide the id from URL.

Laravel 5.4: How to set a first and default parameter to route() function

I 'm passing a prefix parameter to all routes on my webiste:
Route::prefix("{param}")->group(function () {
# code...
});
Sometimes I need to call the route() function in the views. The problem is there, because I need to pass the $param as first parameter like:
resources\views\welcome.blade.php
About Us
The question is: I do not need to pass $param in route() function because its not necessary. How to avoid this and do just the following:
About Us
Is there a way to create a middleware and set a "global" configuration to route() function?
By using #William Correa approach, I've created a helper function to setting up a prefix parameter to default Laravel function helper route().
app\Helpers\functions.php
function routex($route, $params = [])
{
if (!is_array($params)) {
$params = [$params];
}
// Set the first parameter to App::getLocale()
array_unshift($params, App::getLocale());
return route($route, $params);
}
Now when I try to get a link to route() by name, just use routex('about-us') and the routex() function will put a prefix parameter like App::getLocale() or anything else you want.
In your Controller you can protect your route like this:
public function __construct()
{
$this->middleware('auth');
}
and than
Route::get('/about', 'yourcontroller#yourmethod')->name('name');
or in your web.php you can declare a group without a prefix like this
Route::namespace('name')->group(function () {
Route::get('/about', 'yourcontroller#yourmethod')->name('name');
});
Yeah, like this:
Route::get('about-us', 'AboutController#getAboutUs')->name('about-us');
Now if you call route('about-us') it will generate url to .../about-us.

Multiple routes to same Laravel resource controller action

I like to use resource controllers in Laravel, as it makes me think when it comes to data modelling. Up to now I’ve got by, but I’m now working on a website that has a public front-end and a protected back-end (administration area).
I’ve created a route group which adds an “admin” prefix, like so:
Route::group(array('before' => 'auth', 'prefix' => 'admin'), function()
{
Route::resource('article', 'ArticleController');
Route::resource('event', 'EventController');
Route::resource('user', 'UserController');
});
And I can access the methods using the default URL structure, i.e. http://example.com/admin/article/1/edit.
However, I wish to use a different URL structure on the front-end, that doesn’t fit into what resource controllers expect.
For example, to access an article, I’d like to use a URL like: http://example.com/news/2014/06/17/some-article-slug. If this article has an ID of 1, it should (under the hood) go to /article/1/show.
How can I achieve this in Laravel? In there some sort of pre-processing I can do on routes to match dates and slugs to an article ID, and then pass that as a parameter to my resource controller’s show() method?
Re-visiting this, I solved it by using route–model binding and a pattern:
$year = '[12][0-9]{3}';
$month = '0[1-9]|1[012]';
$day = '0[1-9]|[12][0-9]|3[01]';
$slug = '[a-z0-9\-]+';
// Pattern to match date and slug, including spaces
$date_slug = sprintf('(%04d)\/(%02d)\/(%02d)\/(%s)', $year, $month, $day, $slug);
Route::pattern('article_slug', $date_slug);
// Perform the route–model binding
Route::bind('article_slug', function ($slug) {
return Article::findByDateAndSlug($date_slug);
});
// The actual route
Route::get('news/{article_slug}', 'ArticleController#show');
This then injects an Article model instance into my controller action as desired.
One simple solution would be to create one more route for your requirement and do the processing there to link it to the main route. So, for example:
//routes.php
Route::get('/arical/{date}/indentifier/{slug}', array (
'uses' => 'ArticleController#findArticle'
));
//ArticleContoller
public function findArticle($date,$slug){
$article = Article::where('slug','=','something')->first(); //maybe some more processing;
$article_id = $article->id;
/*
Redirect to a new route or load the view accordingly
*/
}
Hope this is useful.
It seems like if Laravel 4 supports (:all) in routing, you would be able to do it with ease, but unfortunately (:all) is not supported in Laravel 4.
However, Laravel 4 allows detecting routes by regular expression, so we can use ->where('slug', '.*').
routes.php: (bottom of the file)
Route::get('{slug}', 'ArticleController#showBySlug')->where('slug', '.*');
Since Laravel will try to match the top most route in routes.php first, we can safely put our wildcard route at the bottom of routes.php so that it is checked only after all other criteria are already evaluated.
ArticleController.php:
class ArticleController extends BaseController
{
public function showBySlug($slug)
{
// Slug lookup. I'm assuming the slug is an attribute in the model.
$article_id = Article::where('slug', '=', $slug)->pluck('id');
// This is the last route, throw standard 404 if slug is not found.
if (!$article_id) {
App::abort(404);
}
// Call the controller's show() method with the found id.
return $this->show($article_id);
}
public function show($id)
{
// Your resource controller's show() code goes here.
}
}
The code above assumes that you store the whole URI as the slug. Of course, you can always tailor showBySlug() to support a more advanced slug checking.
Extra:
You could also do:
Route::get('{category}/{year}/{slug}', 'ArticleController#showBySlug')->where('slug', '.*');
And your showBySlug() would just have additional parameters:
public function showBySlug($category, $year, $slug)
{
// code
}
Obviously you can extend to month and day, or other adaptations.

Resources