Laravel 5.4 Chaining to display Auth data - laravel

I have this in my master blade
<?php $user=auth()->user() ?>
{{ $user->id }}
Im using this code to display the ID of my user detail,
Can you suggest a way to remove <?php ?> or atleast a cleaner approach on this auth ?

Just use id() method:
{{ auth()->id() }}
If you need some other property or related data to display, use user() to get current user object:
{{ auth()->user()->name }}

Maybe you can do something like :
{{ auth()->user()->id }}
or if you have Laravel Auth
use Illuminate\Support\Facades\Auth;
Auth::id();

You can try above suggested answered as cleaner approach, but if you want to remove <?php ?>, you can try below code:
{{--*/ $user=auth()->user() /*--}}
I recommend to use above answered cleaner approach.

if you want to store user to variable initialize it on #php. For example
#php($user = auth()->user())
{{ $user->id }}

Related

Laravel revisionable getting a list of all revisions by specific user

I'm using the VentureCraft/revisionable-package and it shows me in the ReadMe how to show the Revisions of a Model that has revisions:
#foreach($account->revisionHistory as $history )
<li>
{{ $history->userResponsible()->first_name }}
changed {{ $history->fieldName() }}
from {{ $history->oldValue() }}
to {{ $history->newValue() }}
</li>
#endforeach
But I want a list of All revisions that are done by a Specific user; how to achieve that? So I can show a History of Revisions that are done by one specific user.
I have never used this package. But based on what I see, you should be able to add this in your User model
public function revisions()
{
return $this->hasMany(\Venturecraft\Revisionable\Revision::class)
}
then
#foreach($user->revisions as $history )
<li>
{{ $user->first_name }}
changed {{ $history->fieldName() }}
from {{ $history->oldValue() }}
to {{ $history->newValue() }}
</li>
#endforeach
As you asked in the comments :
But I'm missing the Entity that's changed in that list.
(optional) I would implement an interface to my revisionable models with something like :
<?php
namespace App\Contracts;
interface RevisionableContract {
public function entityName();
}
Then in all my models that use the RevisionableTrait :
<?php
namespace App\Models;
class MyModel extend Eloquent implements RevisionableContract {
use RevisionableTrait;
// (required)
public function entityName(){
return 'My Entity name';
}
}
Finally :
#foreach($user->revisions as $history )
<li>
{{ $user->first_name }}
changed {{ $history->fieldName() }}
from {{ $history->oldValue() }}
to {{ $history->newValue() }}
on the entity {{ $history->historyOf()->entityName() }}
</li>
#endforeach
historyOf() may return false
Do you also have an idea how I can make a list of all revisions in desc-order with that info of the user?
From the migrations file, I can see that it has created_at and updated_at timestamps.
You have two possibilities :
In your view, you can directly order them on your collection like this :
#foreach($user->revisions->sortByDesc('created_at') as $history )
When you get a lot of revisions for a user, you will probably have performance issues and you will have to paginate them. From your controller, you will have to sort them and paginate them in your query instead of the collection.
public function index()
{
$user = User::find(1);
$revisions = $user->revisions()->orderBy('created_at')->paginate(15);
return view('your.view', compact('user', 'revisions'));
}
I could not use that package but it seems quite easy to understand. If you can show history of a user you should add this to your "User" entity:
public function history()
{
return $this->hasMany(\Venturecraft\Revisionable\Revision::class, 'user_id', 'id');
}
Or if you want to filter a specific morphable entity you should do it like this:
public function historyForUser(User $user)
{
return $this->morphMany(\Venturecraft\Revisionable\Revision::class, 'revisionable')->where('user_id' , '=', $user->getKey())->getResults();
}
I think that answer is corresponded for what you want to do.

Store method not working using resource route

I am having trouble figuring out why my data is not being posted and stored in my database. I have used the resource routes for another form and it works fine, but here for some reason it won't work. Clicking submit just seems to refresh the page, no errors to work from!
So I have a form which gets the workout routines from a database, and on submission I want this to create a new Workout "session" in my database table (called "Workouts"). The form is this:
{{ Form::open(array('url' => '/')) }}
<div class="form-group">
{{ Form::text('workout_name', Input::old('workout_name'), array('class' => 'form-control', 'placeholder' => 'Session Name')) }}
</div>
<div class="form-group">
{{ Form::select('routines', $routine_names, null, array('class' => 'form-control')) }}
</div>
{{ Form::submit('Select Routine', array('class' => 'btn btn-success pull-right')) }}
{{ Form::close() }}
In my HomeController I have this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Routine;
use App\Workout;
class HomeController extends Controller
{
public function index()
{
$routines = Routine::all();
$routine_names = Routine::lists('routine_name');
return view('workout')->with(array('routines'=>$routines, 'routine_names'=>$routine_names));
}
public function store()
{
$workout = new Workout;
$workout->workout_name = Input::get('workout_name');
$workout->save();
}
}
I have a model created for the Workout, and the route for this page is the following:
Route::resource('/', 'HomeController');
I can't figure out where I'm going wrong. The index method in my controller is working, as it is returning the correct view with the data I need. The form also looks OK I think, as I'm posting to the same page, but submitting doesn't seem to carry out the code I have in the store method of the HomeController.
Any help would be appreciated!
Thanks :)
Change your route declaration from:
Route::resource('/', 'HomeController');
To something like this:
Route::resource('/workout', 'WorkoutController');
If you are using the resources controller creator command of php artisan then all the specific routes are created for you. To see all listed routes you can type , php artisan routes. This will show you RESTFUL routes even for your POST method .
And also even you did not created the resources controller and did made the routes with manual way then you can create ,
Route::POST('/workout' , SomeController#post);
I am trying to say , you have to use the different POST method for the form submission .
Hope this will solve your problem . Thanks.

Laravel - How to a try/catch in blade view?

I would like to create a way to compile in a view, the try/catch.
How can I do this in Laravel?
Example:
#try
<div class="laravel test">
{{ $user->name }}
</div>
#catch(Exception $e)
{{ $e->getMessage() }}
#endtry
You should not have try/catch blocks in your view. A view is exactly that: a representation of some data. That means you should not be doing any logic (such as exception handling). That belongs in the controller, once you’ve fetched data from model(s).
If you’re just wanting to display a default value in case a variable is undefined, you can use a standard PHP null coalescing operator to display a default value:
{{ $user->name ?? 'Name not set' }}
You are probably doing something wrong if you need a try..catch in your view. But that does not mean you should never do it. There are exceptions to every rule.
So anyway, here is the answer:
Put raw PHP in your view by using <?php ?> or #php #endphp tags. Then put your try..catch in the raw PHP.
#php
try {
// Try something
} catch (\Exception $e) {
// Do something exceptional
}
#endphp
while i agree with #areed that something is wrong if you have to use a try...catch, there are weird cases where a wrong approach can lead you down that path. One instance is using the same blade to house a paginate() and a get() response. Well, this might help a little.
<?php try{ ?>
//try to show something
{{ $products->links() }}
<?php }catch(\Exception $e){ ?>
// show something else
<?php } ?>

Check if session key exists in Laravel 5.1?

I'm trying to check it a session key has already been set inside a controller. The documentation states that it is possible to check if an item exists in an array and that's it.
http://laravel.com/docs/5.1/session
you can use
if($request->session()->has('key'))
{
}
Has pointed out by #DavidDomain probably the best way of doing it is to use
if(Session::has('...'))
Worked like a charm for me.
you can use Session::has('YOUR_SESSION_KEY') in both blade and controller
controller ex:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Session;
class add_classController extends Controller
{
public function index(){
if (Session::has('YOUR_SESSION_KEY')){
// do some thing if the key is exist
}else{
//the key does not exist in the session
}
}
}
blade ex:
#if (Session::has('YOUR_SESSION_KEY'))
{{-- do something with session key --}}
#else
{{-- session key dosen't exist --}}
#endif
You can do this
if(Session::has('your_key')){
return $next($request);
}
if($request->session()->exists('your_key'){
//
}
Or shorter, without using the Session Facade: if(session()->exists('key_here'))
This works for me
#if (session()->has('hasCoupon'))
[{{ Session::get('hasCoupon')['name'] }}]</span>
#endif
#if ( session::has('message')
{{ session::get('message') }}
#endif
or
#if (session->has->('message'))
{{session->
#endif
Try this new laravel syntax
#if(session()->has('success'))
//rest of code here
#endif

Building drop-down-list in Laravel (without models)

I am trying to make a drop down list in Laravel with the select options being values from my database and I have some issues. In other tutorials in this site, doing drop down list inquires building the models for your database. I have not created model classes and I do not intend to.
Routes.php
Route::get("/user/charname", array(
'as' => 'profile-character',
'uses' => 'ProfileController#dropDownList'
));
ProfileController.php
class ProfileController extends BaseController
{
public function dropDownList()
{
$list = DB::table('characters')->where('char_id', '128')->pluck('char_name');
return View::make('layout.profile')->with('character_options',$list);
}
}
In the profile.blade.php (view)
<div class="selected_char">
<form action="{{ URL::route('profile-character') }}" method="post">
<li>
{{ Form::select('character_options', $list ,Input::old('character_options')) }}
</li>
</form>
</div>
By doing this it says that $list from my view is undefined. Where do I define $list in the view and how will I carry $list from my Controller to the View because this line doesn't seem to do it's job
return View::make('layout.profile')->with('character_options',$list);
You need to use $character_options not $list in the View.
You actually specify that the variable should be 'character_options' in your View::make() call, so you need to refer to it as $character_options.
Additionally, ->lists('char_name') is better than using ->pluck('char_name') as it'll give you the full list. Pluck just returns the first item it finds.
Additionally to that, using ->lists('char_name', 'id') gets you the list keyed by the id column, which would be useful if you were to use this list to determine IDs for a foreign key field. But no biggie if not.
I have partially solved the issues by doing this in my view:
{{ Form::select('list', DB::table('characters')->where('char_id', '128')->lists('char_name') ,Input::old('list')) }}
Personally I do not see it as a viable solution, but a temporary one
{{ Form::select('character_options', $character_options ,Input::old('character_options')) }}
Error: undefined variable character_options
{{ Form::select('character_options', $list ,Input::old('character_options')) }}
Error: undefined variable list
Maybe I do not understand how i send the variable from the Controller to the View.
You need to use lists as mentioned by #alexrussel. Do note that View::make('layout.profile')->with('character_options',$list);, here you are passing the variable $character_options with the value contained in the $list and $list will no longer be available to the view.
ProfileController.php
<?php
class ProfileController extends BaseController
{
public function dropDownList()
{
$list = DB::table('characters')->where('char_id', '128')->lists('char_name');
return View::make('layout.profile')->with('character_options',$list);
}
}
profile.blade.php
<div class="selected_char">
<form action="{{ URL::route('profile-character') }}" method="post">
<li>
{{ Form::select('character_options', $character_options ,Input::old('character_options')) }}
</li>
</form>

Resources