Laravel: How to solve my custom translation's fallback problem - laravel

I know we can use {{ __(messages.welcome) }}. I think that it's troblesome to call by file path and word each and every time.
{{ __(sales.orders.id) }}
{{ __(sales.orders.code) }}
{{ __(sales.orders.first_name) }}
{{ __(sales.orders.last_name) }}
And it's too long.
So I invented a method.
use Lang;
class OrderController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
// Language
$lang = (object)[];
foreach (Lang::get('common/common') as $key => $value) {
$lang->$key = $value;
}
foreach (Lang::get('sales/order') as $key => $value) {
$lang->$key = $value;
}
$data['lang'] = $lang;
In blade:
{{ $lang->code }}
{{ $lang->first_name }}
{{ $lang->last_name }}
Now I found that this has no fallback function. If a string is translated in English, but not in other language, and I visit that language, error shows
Undefined property: stdClass::$first_name ...
Is there any other way to implement fallback translation?

Related

laravel controller returns only 2 values

I have a database with 3 tables. A separate model is connected to each table, and there is a controller that accepts values from all models. On the site page, I will have 3 tables that will be populated from a mysql table.
When I connected 2 models, everything worked fine. But after connecting 3, I get an error
undefined variable: sec_3.
If you delete one of the variables, then everything will work fine. It seems to me that the problem is either with the controller or with the file blade.php but I do not know how to fix it so that everything works properly. How to fix it?
My code:
Controller:
class PreschoolInstitution3Controller extends Controller {
public function index(){
$context=['bbs' =>PreschoolInstitution3::latest()->get()];
$context_2=['s' =>PreschoolInstitution::latest()->get()];
$context_3=['sec_3' => TrainingPrograms::latest()->get()];
return view('our_employees', $context, $context_2, $context_3);
}
}
web.php:
Route::get('/OurEmployees',[PreschoolInstitution3Controller::class,'index'] )->name('OurEmployees');
blade.php:
#foreach ($s as $section_2) <tr> <td>{{$section_2->number}}<td> <td>{{$section_2->fullname }}<td> <td>{{$section_2->post }}<td> <td>{{$section_2->telephone }}</td> <td>{{$section_2->email }}</td>
#endforeach #foreach ($bbs as $section )
{{$section->number}} {{$section->full_name}} {{$section->post}} {{$section->education}} {{$section->category}} {{$section->teaching_experience}} {{$section->professional_development}}
#endforeach #foreach ($sec_3 as $section_3)
{{ $section_3->number }}
{{ $section_3->level }}
{{ $section_3->directions }}
{{ $section_3->type_of_educational_program }}
{{ $section_3->period_of_assimilation }}
{{ $section_3->number_of_students }}
#endforeach
You should pass an array of data to view:
class PreschoolInstitution3Controller extends Controller {
public function index(){
$context = [
'bbs' => PreschoolInstitution3::latest()->get(),
's' => PreschoolInstitution::latest()->get(),
'sec_3' => TrainingPrograms::latest()->get()
];
return view('our_employees', $context);
}
}
https://laravel.com/docs/9.x/views#passing-data-to-views
Another one is that add a second parameter of an array with name to view( ) .
class PreschoolInstitution3Controller extends Controller {
public function index(){
$bbs = PreschoolInstitution3::latest()->get();
$s = PreschoolInstitution::latest()->get();
$sec_3 = TrainingPrograms::latest()->get();
return view('our_employees', [
'bbs' => $bbs,
's' => $s,
'sec_3' => $sec_3
]);
}
}

foreach() argument must be of type array | object, null given (Laravel Livewire)

This code is working fine
public function render(){
$this->products = ProductModel::get();
return view('livewire.product');
}
But when I am trying to paginate using laravel livewire, it gives me an error
public function render(){
return view('livewire.product', [
'products' => ProductModel::paginate(10)
]);
}
Blade File
#foreach ($products as $product)
{{ $product->name }}
{{ $product->price }}
#endforeach
#if(!empty($products))
{{ $products->links() }}
#endif
import this in Component
use Livewire\WithPagination;
class Product extends Component
{
use WithPagination;
....
}
and add in view
#if(!empty($products))
{{ $products->links() }}
#endif
Ohh I got it.Actually I have already use $products variable as a global variable
and when I change $products to other name it works.
Thanks alot...

Attempt to read property "degree" on null

i have created a profile where users can add their education fields.
when there is no value in the database it throws an error. how can i get rid of this ? Attempt to read property "degree" on null.
public function myEducations()
{
return $this->hasMany('App\Models\Education','user_id')->orderByDesc('endDate');
}
controller
public function myProfile(\App\Models\User $user)
{
$user = Auth::user();
$education = $user->myEducations->first();
return view('candidate.profile',compact('user','education'));
blade
{{ $education->degree }} - {{ $education->fieldOfStudy }}
If the users of you application are filling in their education details later only. You should ideally catch this condition when rendering your view. For example you could try the following:
#if ($education)
{{ $education->degree }} - {{ $education->fieldOfStudy }}
#else
<p>Education details not available</p>
#endif
You have to inspect in an if statement $education->degree is not null.
If not null, degree has value, this part will render.
Else, it doesn't have value so else block appears in template.
#if(null !== $education->degree)
{{ $education->degree }} - {{ $education->fieldOfStudy }}
#else
// there is no degree
#endif

Laravel Auth Return

I created a function in users model to return permission and return as obj. but when i type {{ Auth::user()->permission()->outlineAgreements }} it said "htmlspecialchars() expects parameter 1 to be string, object given". How can i fix it ?
PS: inside test value is an array
"{"outlineAgreements":["view"],"purchaseOrder":["view"],"pwra":["view","create","update","delete"]}"
public function permission()
{
$permissions = auth()->user()->getAllPermissions()->pluck('name');
foreach ($permissions as $key => $value) {
$module = last(explode(" ", $value));
$action = current(explode(" ", $value));
$result[$module] = $result[$module] ?? [];
array_push($result[$module], $action);
}
return json_decode(json_encode($result));
}
Php is complaining about an object print. It expects that the data you are instructing it to print is a string.
Use dd to print out the return of the permissions method for debugging. This way you can see more clearly what data you are about to print out.
{{ dd(Auth::user()->permission()) }}
{{ dd(Auth::user()->permission()->outlineAgreements) }}
If your first box represents that payload data, and you need to access and print all outlineAgreements permissions, and it is an array, you can use implode:
{{ implode(', ', Auth::user()->permission()->outlineAgreements) }}
You can loop through that array too:
#foreach(Auth::user()->permission()->outlineAgreements as $permission)
{{ $permission }}
#endforeach
Hope it helped!

Laravel 5, Trying to get property of non-object

My Controller :
public function show($id){
$user_id_1_connections = Connection::whereUser_id_1AndConnection_status($id, 1)->get();
$user_id_2_connections = Connection::whereUser_id_2AndConnection_status($id, 1)->get();
return view('connection.showConnection',['user_id_1_connections' => $user_id_1_connections, 'user_id_2_connections' => $user_id_2_connections]);
}
My Model :
protected $table = 'connections';
protected $fillable = ['user_id_1','user_id_2','connection_status'];
public function user()
{
return $this->belongsTo('App\User');
}
My Blade :
#foreach($user_id_1_connections as $user_id_1_connection)
{{ $user_id_1_connection->user->name }}
{{ $comment->user->name }}
#endforeach
#foreach($user_id_2_connections as $user_id_2_connection)
{{ $user_id_2_connection->user->name }}
#endforeach
I have made foreign key to user_id_1 and user_id_2 to users table.
$table->integer('user_id_1')->unsigned();
$table->foreign('user_id_1')->references('id')->on('users')->onDelete('cascade');
$table->integer('user_id_2')->unsigned();
$table->foreign('user_id_2')->references('id')->on('users')->onDelete('cascade');
But when I'm running this code. It's showing the error :
Trying to get property of non-object.
The problem here is probably that you don't have user assigned to each connection so instead of:
{{ $user_id_1_connection->user->name }}
you should write rather something like this:
{{ $user_id_1_connection->user ? $user_id_1_connection->user->name : 'unknown' }}
same in all other places when you use $x->y->z syntax. To display z you should make sure $x->y is not null

Resources