Laravel subdomains route and controller parametrs - laravel

I have question.
My routes is
Route::group(['domain' => '{account}.'.$domain], function () {
Route::get('/confirmmail/{hash}', 'Auth\RegisterController#confirmEmail');
});
And my controller method is
public function confirmEmail($domain, $hash)
{
$user = User::where('confirm_token', $hash)->firstOrFail();
$affectedRows = $user->update(array('active' => 1));
if ($affectedRows) {
Auth::login($user);
return Redirect::to('http://'.$user->workshop->slug.'.'.config('app.domain'));
} else {
echo "nie";
}
}
In my method I must use two parametrs $domain and $hash, how I must change route to have
function confirmEmail($hash)

You can access the route parameters from the request helper
request()->route('domain')
request()->route('hash')

Related

Authorization isn’t executed in laravel

This is form ‘login’, when I’m enter information in input and after press button ‘login’ I move to page with audit where 0 is authorization isn't executed and 1 is authorization is executed. I'm trying to create authorization in laravel.
I did it in other project in order to understand how it works and then all was good. Now I'm trying to transfer it in my main project but when I am logging in nothing work.
I don't have any mistake, authorization is simply not executed. I will grateful for any help.
Registration function
public function sub(ContactSignup $request){
if(Auth::check()){
return redirect(route('user.mainpage'));
}
$contact = new SignUps();
$contact->name = $request->name;
$contact->surname = $request->surname;
$contact->age = $request->age;
$contact->password = bcrypt($request->password);
$contact->email = $request->email;
$contact->save();
Auth::login($contact);
if($contact){
Auth::login($contact);
return redirect(route('user.sign-up'))->with('success', 'Реєстрація пройшла успішно');
}
}
Function login
public function subin(ContactSignin $request){
if(Auth::check()){
return redirect()->intended(route('user.mainpage'));
}
$contact = $request->only(['email', 'password']);
if(Auth::attempt($contact)) {
dd(1);
}
else {
dd(0);
}
return redirect()->intended(route('user.mainpage'));
}
Web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return redirect()->route('mainpage');
});
Route::name('user.')->group(function(){
Route::view('mainpage', 'mainpage')->middleware('auth')->name('mainpage');
Route::get('/signin', function(){
if(Auth::check()){
return redirect(route('user.mainpage'));
}
return view('signin');
})->name('sign-in');
Route::post('/signin', [\App\Http\Controllers\ContactController::class, 'subin'])->name('sign-in');
Route::get('logout', function(){
Auth::logout();
return redirect('/');
})->name('logout');
Route::get('/signup', function(){
if(Auth::check()){
return redirect(route('user.mainpage'));
}
return view('signup');
})->name('sign-up');
Route::post('/signup', [\App\Http\Controllers\ContactController::class, 'sub'])->name('sign-up');
});
Route::get('/mainpage', function () {
return view('mainpage');
})->name('mainpage');
in your methods inside your controller you have form request class called ContactSignin
in this class you have code
public function authorize()
{
return false;
}
make it true
The form request class is responsible of validating your request ,
also contains an authorize method. Within this method, you may determine if the authenticated user actually has the authority to update a given resource
since you handle authorization logic for the request in the routes by provide
middleware('auth') it is no need to check for use authentication in your form request class
first you don't have route named ('user.mainpage') you have to define it in web.php
second , since you named your rout in
Route::get('/mainpage', function () {
return view('mainpage');
})->name('mainpage');
, you must redirect to the name of the route not to the path
for example if your route is ('/api/main')->name('main') , you have to put the rout name in the redirect method , for example redirect(route('main'));

How to redirect excluding some slug in laravel routing?

I would like to exclude the {user} in slug route
I want to make:
from example.com/user/someslugs
to exclude the {user} in slug route example.com/someslugs
// This my Verify Controller
class VerifyController extends Controller{
public function redirect($user, $slug){
// Get verify
$verify = Verify::slug($slug)->first();
// Check if verify exists
if (!$verify) {
abort(404);
}
// Redirect to url
return redirect($verify->url);
}
}
Function
// MyFunc
if (!function_exists('verify')) {
function verify($uri, $user){
$model = new \App\Models\Verify;
if (!validate_url($uri)) {
return false;
}
$createVerify = function($url) use ($model){
$slug = \Str::random(6);
$new = $model;
$new->url = $url;
$new->slug = $slug;
$new->save();
return $slug;
};
$route = function($slug, $user){
return route('verify', ['user' => $user, 'slug' => $slug]);
};
if (!$verify = $model->url($uri)->first()) {
$slug = $createVerify($uri);
return $route($slug, $user);
}
return $route($verify->slug, $user);
}
}
Route web.php
// MyRouteVerify
Route::get('{user}/{slug}', 'VerifyController#redirect')->name('verify');
The main problem when I remove {user} from route and wrong controller is called.
How can I achieve this? to get the full URL exclude the {user}, (example.com/someslugs)?
Any suggestion? And I would really appreciate some good and relative answer. Thanks!
in case you guarantee that your slug will never match your route, you can put your user route at the end of the web.php file
Example
// route list here
Route::get('/someroute', 'SomeController#somemethod');
// the last route in your web.php file
Route::get('/{slug}', 'VerifyController#redirect')->name('verify');
I hope it's useful

How to get routes list by specific groups in laravel 5?

Hello I am trying to do it like this but it's getting all the routes, I only want the routes from a specific group(s).
This is my code:
<?php
$routes = Routes::getRoutes();
#foreach($routes as $route)
{{ $route->getPath() }}
#endforeach`
Thanks in advance!
Let's create some routes without any groups
Route::get('/', function () {
return view('welcome');
});
Route::get('/load', 'defaultController#load');
Now we'll create some routes with groups
Route::group(['as' => 'admin'], function () {
Route::get('users', function () {
return "users route";
});
Route::get('ravi', function () {
return "ravi route";
});
Now we are going to create a route in this group which will look for the admin group and print all routes that exist in this group.
Route::get('kumar', function () {
$name = 'admin';
$routeCollection = Route::getRoutes(); // RouteCollection object
$routes = $routeCollection->getRoutes(); // array of route objects
Now in our route object, we will look for our named route by filtering the array.
$grouped_routes = array_filter($routes, function($route) use ($name) {
$action = $route->getAction(); // getting route action
if (isset($action['as'])) {
// for the first level groups, $action['as']
// will be a string
// for nested groups, $action['as'] will be an array
if (is_array($action['as'])) {
return in_array($name, $action['as']);
} else {
return $action['as'] == $name;
}
}
return false;
});
// Here we will print the array containing the route objects in the 'admin' group
dd($grouped_routes);
});
});
Now you can copy and paste this in your route folder and you will be able to see the output by hitting your_project_public_folder_url/kumar
I took help from this answer Answer of patricus

Passing route parameter to controller Laravel 5

I'm trying to pass a route parameter to controller, but I get this error : Argument 2 passed to App\Http\Controllers\JurnalController::store() must be an instance of App\Http\Requests\JurnalRequest, none given
Below are the codes ..
Route :
Route::get('/edisi/{id}', 'JurnalController#store');
Controller :
public function store($id, JurnalRequest $request) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
$jurnal = Edisi::findOrFail($id)->jurnal()->create($input);
return redirect('jurnal');
}
So my question is how to pass the route parameter properly ? Thank you
new routes :
Route::get('/', function () {
return view('pages/home');
});
Route::group(['middleware' => ['web']], function () {
Route::get('edisi', 'EdisiController#index');
Route::get('edisi/create', 'EdisiController#create');
Route::get('edisi/{edisi}', 'EdisiController#show');
Route::post('edisi', 'EdisiController#store');
Route::get('edisi/{edisi]', 'EdisiController#edit');
Route::patch('edisi/{edisi}', 'EdisiController#update');
Route::delete('edisi/{edisi}', 'EdisiController#destroy');
});
Route::get('/edisi/{id}', 'JurnalController#storejurnal');
Route::group(['middleware' => ['web']], function () {
Route::get('jurnal', 'JurnalController#index');
Route::get('jurnal/create', 'JurnalController#create');
Route::get('jurnal/{jurnal}', 'JurnalController#show');
Route::post('jurnal', 'JurnalController#storejurnal');
Route::get('jurnal/{jurnal}/edit', 'JurnalController#edit');
Route::patch('jurnal/{jurnal}', 'JurnalController#update');
Route::delete('jurnal/{jurnal}', 'JurnalController#destroy');
});
new storejurnal method :
public function storejurnal(JurnalRequest $request, $id) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
//Insert data jurnal
$jurnal = Edisi::findOrFail($id)->jurnal()->create($input);
return redirect('jurnal');
}
When you are using resource controller, the store method does not accept any other argument except the Request instance. Try changing the method name or remove the second argument. store() method be default accepts post requests not get requests. Either put your route on top of the resource controller or change the method name.
Route::get('/edisi/{id}', 'JurnalController#store');
Route::resource('jurnals', 'JurnalController');
I hope this helps.
The correct format is:
public function store(JurnalRequest $request, $id) {
// your code
}
If you receive an argument such as Missing argument 2 as suggested in your comments, it means that either you aren't generating the routes correctly, or the url doesn't include the id segment.

Routing to controller with optional parameters

I'd like to create a route that takes a required ID, and optional start and end dates ('Ymd'). If dates are omitted, they fall back to a default. (Say last 30 days) and call a controller....lets say 'path#index'
Route::get('/path/{id}/{start?}/{end?}', function($id, $start=null, $end=null)
{
if(!$start)
{
//set start
}
if(!$end)
{
//set end
}
// What is the syntax that goes here to call 'path#index' with $id, $start, and $end?
});
There is no way to call a controller from a Route:::get closure.
Use:
Route::get('/path/{id}/{start?}/{end?}', 'Controller#index');
and handle the parameters in the controller function:
public function index($id, $start = null, $end = null)
{
if (!$start) {
// set start
}
if (!$end) {
// set end
}
// do other stuff
}
This helped me simplify the optional routes parameters (From Laravel Docs):
Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value:
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Route::get('user/{name?}', function ($name = 'John') {
return $name;
});
Or if you have a controller call action in your routes then you could do this:
web.php
Route::get('user/{name?}', 'UsersController#index')->name('user.index');
userscontroller.php
public function index($name = 'John') {
// Do something here
}
I hope this helps someone simplify the optional parameters as it did me!
Laravel 5.6 Routing Parameters - Optional parameters
I would handle it with three paths:
Route::get('/path/{id}/{start}/{end}, ...);
Route::get('/path/{id}/{start}, ...);
Route::get('/path/{id}, ...);
Note the order - you want the full path checked first.
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Find more details here (Laravel 7) : https://laravel.com/docs/7.x/routing#parameters-optional-parameters
You can call a controller action from a route closure like this:
Route::get('{slug}', function ($slug, Request $request) {
$app = app();
$locale = $app->getLocale();
// search for an offer with the given slug
$offer = \App\Offer::whereTranslation('slug', $slug, $locale)->first();
if($offer) {
$controller = $app->make(\App\Http\Controllers\OfferController::class);
return $controller->callAction('show', [$offer, $campaign = NULL]);
} else {
// if no offer is found, search for a campaign with the given slug
$campaign = \App\Campaign::whereTranslation('slug', $slug, $locale)->first();
if($campaign) {
$controller = $app->make(\App\Http\Controllers\CampaignController::class);
return $controller->callAction('show', [$campaign]);
}
}
throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
});
What I did was set the optional parameters as query parameters like so:
Example URL:
/getStuff/2019-08-27?type=0&color=red
Route:
Route::get('/getStuff/{date}','Stuff\StuffController#getStuff');
Controller:
public function getStuff($date)
{
// Optional parameters
$type = Input::get("type");
$color = Input::get("color");
}
Solution to your problem without much changes
Route::get('/path/{id}/{start?}/{end?}', function($id, $start=null, $end=null)
{
if(empty($start))
{
$start = Carbon::now()->subDays(30)->format('Y-m-d');
}
if(empty($end))
{
$end = Carbon::now()->subDays(30)->format('Y-m-d');
}
return App\Http\Controllers\HomeController::Path($id,$start,$end);
});
and then
class HomeController extends Controller
{
public static function Path($id, $start, $end)
{
return view('view');
}
}
now the optimal approach is
use App\Http\Controllers\HomeController;
Route::get('/path/{id}/{start?}/{end?}', [HomeController::class, 'Path']);
then
class HomeController extends Controller
{
public function Path(Request $request)
{
if(empty($start))
{
$start = Carbon::now()->subDays(30)->format('Y-m-d');
}
if(empty($end))
{
$end = Carbon::now()->subDays(30)->format('Y-m-d');
}
//your code
return view('view');
}
}

Resources