Laravel 5 : How to get path name from URL? - laravel-5

In laravel , I come across a situation where I need to get the path name from url.
e.g.
www.example.com/timeslot
In above example I want to fetch "timeslot" in my controller
public function login()
{
$url = URL::current();
echo "timeslot"; //I want to print only "timeslot" here.
}

Hello to retrieve a uri segment in laravel use it
$segment = Request::segment(1);
inside the blade view like this
{!! Request::segment(1) !!}
this will return the first segment of your project uri
www.example.com/timeslot
timeslot

simply use
$request->path();
The path method returns the request's path information. So, if the incoming request is targeted at www.example.com/timeslot, the path method will return timeslot.
See: https://laravel.com/docs/5.4/requests

This should give you the path
public function login(){
$url =\Request::path();
echo $url;
}

You need to request the path, like so.
public function test(Request $request) {
$url = $request->path();
return view('home')->with('url', $url);
}
and in your view
{{ $url }}

Related

Laravel 6.2 - Dynamically Call a Controller action

I have used a code from Internet to call controller action dynamically. Here is the code for that, and is used in web.php. But I dont fully understand what it does.
Route::match(['get', 'post'], '{controller}/{action?}/{params1?}/{params2?}', function ($controller, $action = 'index', $params1 = '',$params2 = '') {
$params = explode('/', $params1);
$params[1] = $params2;
$app = app();
$controller = $app->make("\App\Http\Controllers\\" . ucwords($controller) . 'Controller');
return $controller->callAction($action, $params);
})->middleware('supadminauth');
Can someone explain?
Route::match(['get', 'post'], '{controller}/{action?}/{params1?}/{params2?}', function ($controller, $action = 'index', $params1 = '',$params2 = '') {
The first line looks at the request to see whether it is a get or post request, if it is some other types of request that means it does not match and will not proceed further. Then the url are separated into 4 parts corresponding by their name and passed into variables with the same name i.e. $controller, $action, $param1 and $params2 where the last 3 variables do not need to be present (with ? at the end of the name).
$params = explode('/', $params1);
$params[1] = $params2;
I believe this is a crude way to create an array of parameters as $params where the following would be more appropriate.
$params = [$params1, $params2];
.
$app = app();
$controller = $app->make("\App\Http\Controllers\\" . ucwords($controller) . 'Controller');
Then load the relevant controller.
return $controller->callAction($action, $params);
And run the corresponding action and passing all the parameters with it.
Hope this makes sense.
This is example of use it:
If you have controller like bellow:
class AdminController extends Controller {
public function index(){ //sample 0, sample 1
...
}
public function view($param1){ //sample2 , sample3
...
}
}
There is some sample route for calling them
sample0: yoursite.com/admin
sample1: yoursite.com/admin/index
sample2: yoursite.com/admin/view
sample3: yoursite.com/admin/view/5
Notice in your question ? in {action?} means it can either have value or not. Other things is simple and clear. Do you need more explaination?

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
}

Laravel unlink method

can someone tell me how to unlink image from public path when product is deleted.
My current code which does not work:
public function destroy($id)
{
$product = Product::findOrFail($id);
$image_path = '/uploads/products/' . $product->image;
if(file_exists($image_path)){
unlink($image_path);
}
$product->delete();
}
Also tried:
$product = Product::findOrFail($id);
if(file_exists($product->image)){
unlink($product->image);
}
$product->delete();
Also I am using accessor so my $product->image is returning:
"http://myeshop.local/uploads/products/1593902362bluesocksupd.jpg"
Here is accessor code:
public function getImageAttribute($image){
return asset($image);
}
use model deleted event
//Product Model
protected static function boot()
{
parent::boot();
static::deleted(function($product){
// getOriginal skip accessor
$image = public_path('uploads/products/' . $product->getOriginal('image'));
if(file_exists($image)) {
unlink($image);
}
});
}
unlink($path) is a PHP function. It will delete a file located at a local path. According to your question the value of $product->image is the complete URL to the image. If it is then the following is true:
$product = Product::findOrFail($id);
$image_path = '/uploads/products/' . $product->image;
// $image_path = '/uploads/products/http://myeshop.local/uploads/products/1593902362bluesocksupd.jpg'
// and it needs to point to '/PATH/TO/LARAVEL/uploads/products/1593902362bluesocksupd.jpg'
// the following file_exists() will return false
if(file_exists($image_path)){
unlink($image_path); // so you never get here
}
There are some quick and dirty ways to fix this, but the best thing to do is to have the $product->image property point to just the name of the file. Then in your view apply the file name to the /uploads/products/ directory on the web server.
Doing this will allow you to apply the /uploads/products/ local path and have a better time finding the file you want to delete. I'm assuming the uploads directory is in your Laravel public directory so you'd want to do something like this:
// $product->image must point to the filename only: 1593902362bluesocksupd.jpg
// The file_exists should evaluate to true and unlink() will work.
$image_path = public_path('uploads/products/' . $product->image);
if(file_exists($image_path)){
unlink($image_path);
}
In your Blade template view you'd need to show the product image using something like this:
<img src="{{ url('/uploads/products/' . $product->image) }}" />
Storing a complete URL in your database doesn't scale well if you wanted to develop another website or reuse this code on another project. This way you can let Laravel manage where the URL or local file system is.
You could use PHP's unlink() method.
But if you want to do it the Laravel way, use the Storage::delete method instead :
use Illuminate\Support\Facades\Storage;
public function destroy($id)
{
$product = Product::findOrFail($id);
$image_path = public_path('uploads/products/' . $product->image);
if(file_exists($image_path)){
Storage::delete($image_path);
}
$product->delete();
}

Laravel passing data to page

I am trying to pass data to Controller of Laravel. here is how I do that :
in PagesController::
class PagesController extends Controller
{
public function contact(){
$data="some random ";
return view('contact',compact("data"));
}
}
now in contact.blade.php :
contact pages {{ $data }}
and it s hows
Whoops, looks like something went wrong.
What may be a problam?
try this
public function contact()
{
$data = 'some random';
return View('contact')->with('data' , $data );
}
make sure that the view works fine (if its inside a folder use return View('foldername.contact')
make sure that your view name is contact.blade.php (check uppercase letters)
and inside your view
this is my {{ $data }}

Laravel 4 : Route to localhost/controller/action

I'm more or less new to Laravel 4. I've never used routes before but normally what I'm used to is url/controller/action and then the backend routing for me. I've read the documentation for routes and controllers a few times as well as read through some tutorials and so, I'm trying to figure out how to get this to work without writing a route for every controller and action.
I tried something like
Route::get('{controller}/{action}', function($controller, $action = 'index'){
return $controller."#".$action;
});
Now then, I know this is wrong since it doesn't work, but what am I missing? On most tutorials and stuff I'm seeing an route for more or less every controller and action like:
Route::get('/controller/action' , 'ControllerName#Action');
Which seems silly and like a waste of time to me.
Is there anyway to achieve what I want?
If you are looking for a more automated routing, this would be the Laravel 4 way:
Route:
Route::controller('users', 'UsersController');
Controller (in this case UsersController.php):
public function getIndex()
{
// routed from GET request to /users
}
public function getProfile()
{
// routed from GET request to /users/profile
}
public function postProfile()
{
// routed from POST request to /users/profile
}
public function getPosts($id)
{
// routed from GET request to: /users/posts/42
}
As The Shift Exchange mentioned, there are some benefits to doing it the verbose way. In addition to the excellent article he linked, you can create a name for each route, for example:
Route::get("users", array(
"as"=>"dashboard",
"uses"=>"UsersController#getIndex"
));
Then when creating urls in your application, use a helper to generate a link to a named route:
$url = URL::route('dashboard');
Links are then future proofed from changes to controllers/actions.
You can also generate links directly to actions which would still work with automatic routing.
$url = URL::action('UsersController#getIndex');
app\
controllers\
Admin\
AdminController.php
IndexController.php
Route::get('/admin/{controller?}/{action?}', function($controller='Index', $action='index'){
$controller = ucfirst($controller);
$action = $action . 'Action';
return App::make("Admin\\{$controller}Controller")->$action();
});
Route::get('/{controller?}/{action?}', function($controller='Index', $action='index'){
$controller = ucfirst($controller);
$action = $action . 'Action';
return App::make("{$controller}Controller")->$action();
});
I come from .Net world and routing is typically done:
/{Controller}/{action}/{id}
Which looks like:
/Products/Show/1 OR /Products/Show/Beverages
In Laravel I accomplish this routing like so:
Route::get('/{controller?}/{action?}/{id?}', function ($controller='Home', $action='index', $id = null) {
$controller = ucfirst($controller);
return APP::make("{$controller}Controller")->$action($id);
});
The controller would look roughly like so:
class ProductsController extends BaseController {
public function Show($id) {
$products = array( 1 => array("Price" => "$600","Item" => "iPhone 6"),
2 => array("Price" => "$700", "Item" => "iPhone 6 Plus") );
if ($id == null) {
echo $products[1]["Item"];
} else {
echo $products[$id]["Item"];
}
}
}

Resources