Laravel custom component parameter parsing issue - php

In my Laravel (7.x) application. I am trying to create a component for links:
Component:
<a class="links" href="{{ $route }}" title="{{ $title ?? null }}">
#isset($icon)
<i class="{{ $icon }}"></i>
#endisset
#isset($caption)
<span>{{ $caption }}</span>
#endisset
</a>
<x-link icon="{{ $icon }}" route="{{ route("admin.{$route}.create") }}" />
OR
<x-link icon="{{ $icon }}" route="{{ route("admin." . $route. ".create") }}" />
OR
<x-link icon="{{ $icon }}" route="{!! route("admin.{$route}.create") !!}" />
OR
<x-link icon="{{ $icon }}" route="{!! route("admin." . $route. ".create") !!}" />
And getting this issue:
syntax error, unexpected token "endif", expecting end of file (View: \path)
However, if I do this, then it works:
$url = route("admin.{$route}.create");
...
<x-link icon="{{ $icon }}" route="{{ $url }}"></x-link>
I am not a fan of declaring the variables just for single use, I like to pass the value directly. Therefore, I prefer the first method.
Why is this simple code not working..?

I found that the parameters work better, if the values are bind with them.
<x-link icon="{{ $icon }}" :route="route('admin.' . $route . '.create')" />
Additionally... In case, if the multiple values are required:
<x-link icon="{{ $icon }}" :route="route('admin.' . $route . '.create')" :params="[
'key1' => 'value1',
'key2' => [
...
],
]" />

Related

Property [medias] does not exist on this collection instance

I have a website that works on localhost, but not on production server.
I got this error :
Property [medias] does not exist on this collection instance
This is a portion of the foreach loop that works on localhost :
#foreach($critiques as $critique)
<div class="max-w-md bg-white rounded-xl shadow-md overflow-hidden md:max-w-2xl">
<div class="md:flex">
<div class="md:shrink-0">
#if (preg_match('/img/', $critique->medias->picture) )
<img class="h-48 w-full object-cover md:h-full md:w-48" src="{{ $critique->medias->picture ?? '' }}" alt="{{ $critique->medias->title }}">
#elseif(!preg_match('/img/', $critique->medias->picture) && $critique->medias->plateform != 'Cinéma' )
<img class="h-48 w-full object-cover md:h-full md:w-48" src="{{ $critique->medias->picture ?? '' }}" alt="{{ $critique->title }}">
I do not understand what happens.
$critique is not an object but a collection. I guess that this is not a simple Model collection but you are doing some manipulation like grouping.
$critiques are probably a collection of collections and you need to do one more loop.

Getting data from database in web routes - Laravel

I have this Laravel application, in which I want to display the name of the logged in user in the pages.. Thing is, I'm getting the data in the web.php file, like this:
Route::get('/', function () {
$welcomeNames = DB::table('users')->get();
return view('welcome', ['welcomeNames' => $welcomeNames]);
});
And then, in my welcome.blade.php, I return the data like this:
#if (!Auth::guest())
#foreach($welcomeNames as $key => $data)
#if ($data->name == Auth::user()->name )
<tr>
<th>{{$data->name}}</th>
</tr>
#endif
#endforeach
<a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('frm-logout').submit();" class="text-sm text-gray-700 dark:text-gray-500 underline">
Logout
</a>
<form id="frm-logout" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
#else
#endif
My question is: is this a safe practice? I don't know if getting the data from the DB in my route is safe. Thanks in advance!
It is safe as long as you do not show it somewhere where it doesn't belong. But its bad practice and shouldn't be done if not really needed. AND controllers are way more organised in any way.

String replace in Laravel Blade

I have project in Laravel 5.8.
I have this code:
<a href="{{ route('user', ['url_address' => $user->url_address, 'id' => $user->id]) }}"><img
src="{{ $user->images->first()->path ?? $placeholder }}"
class="img-responsive center" alt="{{ $user->name }}"></a>
This return me:
<img src="upload/images/UserImage/c561b1742783ed038521c488d1cd59a1.jpg" class="img-responsive center" alt="angel">
I need replace this:
upload/images/UserImage/c561b1742783ed038521c488d1cd59a1.jpg
to:
upload/images/UserImage/thumbs3/c561b1742783ed038521c488d1cd59a1.jpg
How can I make it?
You have a few options here. You could update your DB data, add a new column to store the thumb path, or modify the existing path in place.
Here's one way to do it using https://laravel.com/docs/5.8/helpers#method-str-replace-first
<?php
use Illuminate\Support\Str;
...
$search = 'upload/images/UserImage/';
$replace = 'upload/images/UserImage/thumbs3/';
$original = $user->images->first()->path;
$replaced = Str::replaceFirst($search, $replace, $original );
// Now, use `$replaced` as your image src.
<a href="{{ route('user', ['url_address' => $user->url_address, 'id' => $user->id]) }}">
<img src="{{ $replaced ?? $placeholder }}"
class="img-responsive center" alt="{{ $user->name }}">
</a>
I should also mention, that in my experience it is easier to maintain a system where all you store in the DB is the file name of the uploaded document. In this case, c561b1742783ed038521c488d1cd59a1.jpg.
Your views then control which directory to look in: ...public_path('upload/images/thumbs/' . $user->profile_image)

Laravel - Views - router() doesn't work or I just dumb

Here is my web.php
Route::get('read/{book_id}/{part_id}', 'BookPartController#show')->name('read');
And this is the Views
<a href="{{ route('read', [$part->book_id, $part->part_id]) }}">
I wanna expect for the result is mysite.com/read/808/121, though the result is this mysite.com/read/808
try this, adding the keys to the array:
<a href="{{ route('read',
['book_id' => $part->book_id, 'part_id' => $part->part_id]) }}">
Correct way to do it:
<a href="{{ route('read', ['book_id' => $part->book_id, 'part_id' => $part->part_id]) }}">

Page not found error in laravel routing

I am new to laravel, I have written a route
Route::resource('contract', 'ContractController');
Route::group(['prefix' => 'contract'], function () {
Route::get('data', 'ContractController#data');
});
My controller file is :
public function data(Datatables $datatables)
{
$contracts = $this->contractRepository->getAll()
->get()
->map(function ($contract) {
return [
'id' => $contract->id,
'start_date' => $contract->start_date,
'end_date' => $contract->end_date,
'description' => $contract->description,
'name' => '',
'user' => '',
];
});
return $datatables->collection($contracts)
->addColumn('actions', '#if(Sentinel::getUser()->hasAccess([\'contracts.write\']) || Sentinel::inRole(\'admin\'))
<a href="{{ url(\'contract/\' . $id . \'/edit\' ) }}" title="{{ trans(\'table.edit\') }}">
<i class="fa fa-fw fa-pencil text-warning"></i> </a>
#endif
#if(Sentinel::getUser()->hasAccess([\'contracts.read\']) || Sentinel::inRole(\'admin\'))
<a href="{{ url(\'contract/\' . $id . \'/show\' ) }}" title="{{ trans(\'table.details\') }}" >
<i class="fa fa-fw fa-eye text-primary"></i> </a>
#endif
#if(Sentinel::getUser()->hasAccess([\'contracts.delete\']) || Sentinel::inRole(\'admin\'))
<a href="{{ url(\'contract/\' . $id . \'/delete\' ) }}" title="{{ trans(\'table.delete\') }}">
<i class="fa fa-fw fa-times text-danger"></i></a>
#endif')
->removeColumn('id')
->escapeColumns( [ 'actions' ] )->make();
}
When I am running with url contract/data then I am getting 404 not found error. In console I am getting error also
No query results for model [App\Models\Contract].
Please help me to resolve the issue
Just remove Route::resource('contract', 'ContractController'); or put that after Route::group(['prefix' => 'contract'], function () {
Route::get('data', 'ContractController#data');
}); like so:
Route::group(['prefix' => 'contract'], function () {
Route::get('data', 'ContractController#data');
});
Route::resource('contract', 'ContractController');
You get 404 on route /contract/data because the router is actually directed into contract/{contract} in ContractController#show from the upper routes on Route::resource('contract', 'ContractController');

Categories