Get specific value Laravel - php

I have car table with status field and there's "available", and "breakdown".
I also got fleet CRUD, once I add fleet I want to show car with only "available" status. what should I add ?
here's my fleet controller code :
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Models\Fleet;
use App\Models\Car;
use App\Models\Attendance;
use App\Helpers\Enums\FleetStatus;
use App\Models\AttendanceDetail;
use Illuminate\Http\Request;
use Yajra\Datatables\Datatables;
use App\Http\Controllers\Base\MasterController;
use Route;
use Illuminate\View\View;
class FleetController extends MasterController
{
protected $detailView = 'fleet.show';
protected $indexView = 'fleet.index';
protected $createView = 'fleet.form';
protected $editView = 'fleet.form';
protected $routeBindModel = 'fleet'; //Route Model Binding name in RouteServiceProvider
protected $redirectPageWhenFormSuccess = 'fleet.index'; //Route Name
protected $title = 'Fleet';
public function save(Request $request, $obj = null) {
if (!$obj) {
$obj = new Fleet;
}
return $this->saveHandler($request, $obj);
}
//Must have this method if need datatable;
public function datatableBuilder($obj = null) {
return Fleet::query();
}
public function makeDatatable($obj) {
return Datatables::of($obj)
->addColumn('action', function ($model) {
return $this->makeActionButtonsForDatatable($model);
})
->editColumn('status', function($model){
return FleetStatus::getString($model->status);
})
->make(true);
}
public function render(View $view, $route = null, $obj = null, $method = 'POST') {
$statusList = FleetStatus::getArray();
$carStatusList = Car::pluck('plate_no', 'id');
$attendanceList = Attendance::pluck('driver_id', 'id');
$workingHourList = Attendance::pluck('working_hours', 'id');
$view->with(compact('statusList', 'carStatusList', 'attendanceList', 'workingHourList'));
return parent::render($view, $route, $obj, $method);
}
}
here's my add form code :
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label>Car </label>
{!! Form::select('car_id', $carStatusList, null, array('class' => 'form-control')) !!}
</div>
</div>

Have you try this:
$carStatusList = Car::where('status', 'available')->pluck('plate_no', 'id')

In your model add a scope
public function scopeAvailable($query){
return $query->where('status', '=', 'available');
}
And then wherever you need to use it:
Car::available()->get()
or
Car::available()->pluck('plate_no' , 'id');
More info here: https://laravel.com/docs/5.3/eloquent#query-scopes

If I understand your question correctly, this will create a list of available cars:
Car::where('status','available')->pluck('plate_no', 'id');

Related

Parameter count error when using #can Blade directive

I'm having the following error when I try to check a permission using policies:
Too few arguments to function App\Policies\AnswerPolicy::view(), 1 passed in /Users/georgio/Projects/Laravel/municipality-app/vendor/laravel/framework/src/Illuminate/Auth/Access/Gate.php on line 710 and exactly 2 expected (View: /Users/georgio/Projects/Laravel/municipality-app/resources/views/layouts/loggedin.blade.php)
AnswerPolicy
<?php
namespace App\Policies;
use App\Answer;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class AnswerPolicy
{
use HandlesAuthorization;
public function view(User $user, Answer $answer)
{
return true;
}
public function edit(User $user)
{
return true;
}
public function create(User $user)
{
return true;
}
public function delete(User $user)
{
return true;
}
public function update(User $user)
{
return true;
}
}
AnswersController
<?php
namespace App\Http\Controllers;
use App\Question;
use App\Answer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AnswersController extends Controller
{
public function index()
{
$this->authorize('view');
return view('answers.show')->with('questions', Question::all());
}
public function create($questionId)
{
$this->authorize('view-submit-answer');
return view('answers.create')->with('question',Question::find($questionId));
}
public function store()
{
$this->authorize('');
$this->validate(request(),[
'answer' => 'required',
]);
$data = request()->all();
$answer = new Answer();
$answer->answer = $data['answer'];
$answer->question_id = $data['question_id'];
$answer->user_id = Auth::id();
$answer->save();
return redirect('/questions/answers');
}
public function edit($answerId)
{ $this->authorize('view-edit-answer');
return view('answers.edit')->with('answer', Answer::find($answerId));
}
public function update($answerId)
{
$this->validate(request(),[
'answer' => 'required',
]);
$data = request()->all();
$answer = Answer::find($answerId);
$answer->answer = $data['answer'];
$answer->save();
return redirect('/answers-question');
}
public function destroy($questionID)
{
$this->authorize('delete-answer');
$answer = Answer::where('question_id', $questionID)->where('user_id', Auth()->id());
$answer->delete();
return redirect('/questions/answers');
}
}
loggedin.blade.php
This is only the part of my code that is causing the error
#can('view', App\Answer::class)
<li>
<a href="/questions/answers">
<span><i class="fa fa-pencil"></i></span>
<span>Answer Question</span>
</a>
</li>
#endcan
I even tried replacing $answer with App\Answer::class and I still had the exact same error.
You can check the full error stack at:
https://flareapp.io/share/xPQQQXP1#F66
The documentation says
When defining policy methods that will not receive a model instance, such as a create method, it will not receive a model instance. Instead, you should define the method as only expecting the authenticated user
I don't see an Answer instance inside your #can statement there. Does one exist? If so, you should be doing this:
#can('view', $answer)
Or, if one doesn't exist at that point, define your method like this
public function view(User $user)
And call it like this:
#can('view', \App\Answer::class)

Call to a member function links() on null in laravel

I'm trying to make tags filter on my page, but I have an error says Call to a member function links() on null.
Thank you for anything you can do to help.
This is my controller:
<?php
public function index(Request $request)
{
if($request->has('cari')) {
$forums = \App\Forum::where('title','LIKE','%'.$request->cari.'%')->paginate(5);
} elseif($request->has('tags')) {
$tag = Tag::find($request->tags);
$forums = $tag->forums;
} else {
$forums = Forum::paginate(5);
}
$populars = DB::table('forums')
->join('comments','forums.id','=','comments.commentable_id')
->select(DB::raw('count(commentable_id) as count'),'forums.id','forums.title','forums.slug')
->groupBy('id','title','slug')
->orderBy('count','desc')
->take(5)
->get();
return view('forum.index', compact('forums','populars'));
}
And this is my link in view:
<div class="row justify-content-center">
{!! $forums->links() !!}
</div>
This is my forum model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class forum extends Model
{
public function tags()
{
return $this->belongsToMany('App\Tag');
}
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}

Laravel not getting Accessor Trying to get property on a non-object

I'm trying to get the value of a map object to check if a user made a rating or not.
{{ $book->rated }} is returning neither false or true.
in tinker
$book->getTypeAttribute(); PHP Notice: Trying to get property of
non-object in /Applications/MAMP/htdocs/elirating/app/Book.php on line
40
This method needs to get the type of the rating, the default value is set to false
public function getTypeAttribute(){
return Rate::where('type', $this->attributes['id'])->where('user_id',auth()->user()->id) === self::RATED;
}
Book.php
use Illuminate\Database\Eloquent\Model;
use willvincent\Rateable\Rateable;
use App\User;
use App\Rate;
class Book extends Model
{
use Rateable;
const RATED = "true";
const NOT_RATED = "false";
protected $fillable = [ 'user_id', 'title', 'description'];
public function scopeGetBook($query, $book_name )
{
return $query->where('slug', $book_name );
}
public function setTitleAttribute($value)
{
$this->attributes['title'] = $value;
$this->attributes['slug'] = str_slug($value);
}
public function scopeGetBookUser($query, $user_id)
{
return $query->where('user_id', $user_id )->first();
}
public function getTypeAttribute(){
return Rate::where('type', $this->attributes['id'])->where('user_id',Auth()->user()->id) === self::RATED;
}
Rate.php
<?php
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
use willvincent\Rateable\Rateable;
class Rate extends Model
{
protected $fillable = [
'user_id',
'type',
'rating'
];
public $timestamps = false;
protected $table = 'ratings';
}
BookController.php (this is how the type is being set, and how im trying to retrieve the value)
public function rate(Request $request, $book_id)
{
$book = Book::find($book_id);
$rating = $book->ratings()->where('user_id', auth()->user()->id)->first();
if(is_null($rating)){
$ratings = new Rating();
$ratings->rating = $request['rating'];
$ratings->user_id = auth()->user()->id;
$ratings->type = Book::RATED;
$book->ratings()->save($ratings);
return json_encode($book);
}
else{
return response()->json(['status' => 'You already left a review']);
}
}
public function show($book_name)
{
$books = Book::with('ratings')->GetBook($book_name)->get();
$data = $books->map(function(Book $book){
$book['rated'] = $book->getTypeAttribute();
return $book;
});
return view('books.show', compact('data', $data));
}
HTML
<div id="rateYo" data-rateyo-rating="{{ $book->userSumRating or 0}}" data-rateyo-read-only="{{ $book->rated }}" > ></div>
image(the read-only attribute needs to have either true of false) it doesn't show neither.
You need to call first or get on the query in the accessor:
return Rate::where(['type' => $this->getKey(), 'user_id' => auth()->id()])->first()
Also, when using accessors, you don't call the full function, as in getTypeAttribute, you only use the attribute name, type.
// wrong
$book['rated'] = $book->getTypeAttribute();
// right
$book['rated'] = $book->type;
However, I think what you should be doing to find if a user has left a rating is to use the exists or doesntExist query functions. For example:
// this will return true/false
public function getRatedAttribute()
{
return Rate::where(['type' => $this->getKey(), 'user_id' => auth()->id()])->exists();
}
Append the attribute to the Book model:
// this will add the attribute to each book in the query result.
protected $appends = ['rated']; // or type
Then you can simply use:
$book->rated; // true if a rating exists, otherwise false.

Laravel Undefined offset error

I just finishing my blog, using laravel, and I want to add a comment feature on it, but i got few errors like this, can anyone help me, please??,
sorry for my English, English is not my native language,
Thank you :)
(1/1) ErrorException
Undefined offset: 1
Here is my AdminBlog.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class AdminBlog extends Model
{
protected $table = 'admin';
protected $fillable = ['title','text','images','slug'];
public function comment(){
return $this->hasMany('App\Comment');
}
}
Comment.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table = 'comment';
protected $fillable = ['name','email','text','post_id'];
public function post(){
return $this->belongsTo('App\AdminBlog');
}
}
BlogController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\AdminBlog;
use App\Comment;
class BlogController extends Controller
{
//Index
public function index(){
$post = AdminBlog::all();
return view('blog/index', compact('post'));
}
//Show
public function show($id){
$post = AdminBlog::findOrFail($id);
$comment = Comment::all();
//dd($comment);
return view('blog/show', ['post' => $post,
'comment' => $comment]);
}
}
show.blade.php
<div class="col-md-12 post-comment-show">
#foreach($post->comment() as $list)
<p>{{ $list->text }}</p>
#foreach
</div>
You should use:
<div class="col-md-12 post-comment-show">
#foreach($post->comment as $list)
<p>{{ $list->text }}</p>
#foreach
</div>
Note that, you have used comment(). Also, you should use a plural name for a hasMany relationship, so comment should be comments.
Also, in your show method, you should use something like the following:
public function show($id)
{
$post = AdminBlog::with('comment')->findOrFail($id);
return view('blog/show', ['post' => $post]);
}
Try the following
$post->comment()->get()
or
$post->comment
when calling a relationship with ()it returns a instance of the query builder and allows you to filter the object. If you remove the call it without () it returns you a collection which is array accessible
Another suggestion if you have many comments you should name your relationship plural.
in this case:
public function comments(){
return $this->hasMany('App\Comment');
}
// Use it like this
$post->comments
You need to change your show function:
public function show($id){
$post = AdminBlog::findOrFail($id);
$comment = Comment::all();
//dd($comment);
return view('blog/show', ['post' => $post,
'comment' => $comment]);
}
TO
public function show($id){
$post = AdminBlog::with('comment')->where('admin.id',$id)->get();
return view('blog/show', compact('post'));
}
Hope this work for you!

Class not found with laravel?

today I am trying to fix the following error. It is telling me for some weird reason that the class for my relationship in laravel does not exist? I am not sure why as the code looks perfectly fine to me.
Class 'App\Database\Website\Roleplay\GovermentRole' not found
Where it is happening:
{{ $governmentMember->government_role->government_title }}
Full code:
#if ($higherGovernment->count() > 0)
#foreach ($higherGovernment as $governmentMember)
<div class="col-md-10">
<div class="col-md-12" style="margin-left:-40px;">
<div class="col-md-1" style="margin-top:-16px;"><img src="http://mywebsite.com/images/get_character_look.php?look={{ $governmentMember->user->look }}&size=b&direction=3&head_direction=3"></div>
<div class="col-md-9" style="margin-left:40px;">
<h4>{{ $governmentMember->government_role->government_title }}<small>The Crown</small></h4>
<p><font color="#aaa">Department here</font></p><br>
</div>
</div>
</div>
#endforeach
#else
There are currently no candigates working in this category.
#endif
Here is my Roleplay Stat class, which $governmentMember is an instance of:
<?php
namespace App\Database\Website\User;
use Eloquent;
class Roleplay extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_user_statistics';
public $timestamps = false;
protected $fillable = [];
public function user()
{
return $this->belongsTo('App\Database\Website\User\Player', 'user_id', 'id');
}
public function government_role()
{
return $this->belongsTo('App\Database\Website\Roleplay\GovermentRole', 'government_id');
}
}
Here is my GovernmentRole class:
<?php
namespace App\Database\Website\Roleplay;
use Eloquent;
class GovernmentRole extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_government_roles';
public $timestamps = false;
protected $fillable = [];
public function stats(){
return $this->hasMany('App\Database\Website\User\Roleplay', 'government_id');
}
}
Here is the controller for the blade page:
<?php
namespace App\Http\Controllers\Frontend\User;
use Auth;
use Cache;
use Illuminate\Http\Request;
use App\Database\Website\User\Roleplay;
use App\Database\Website\Roleplay\GovernmentRole;
use App\Database\Website\Roleplay\Life\LifeEvents;
class GovernmentController
{
public function getView()
{
$royalty = Cache::remember('government.royalty', 1, function() {
return GovernmentRole::where('government_type', 'royalty')->first()->stats;
});
$higherGovernment = Cache::remember('government.higher_government', 1, function() {
return GovernmentRole::where('government_type', 'higher_government')->first()->stats;
});
$seniorGovernment = Cache::remember('government.senior_government', 1, function() {
return GovernmentRole::where('government_type', 'senior_ministers')->first()->stats;
});
$juniorGovernment = Cache::remember('government.junior_government', 1, function() {
return GovernmentRole::where('government_type', 'junior_ministers')->first()->stats;
});
return view('frontend.community.government', compact('juniorGovernment', 'seniorGovernment', 'higherGovernment', 'royalty'));
}
}
Sorry to tell you this, but there is a 'typing error' in your relationship method
public function government_role()
{
return $this->belongsTo('App\Database\Website\Roleplay\GovermentRole', 'government_id');
}
You are looking for 'GovermentRole' while the class' name is 'GovernmentRole'. Notice the extra 'n' character after 'r'
The error is because GovermentRole file does not available at specified path i.e.
App\Database\Website\Roleplay\GovermentRole
Make sure the class is in right folder. Then run this command:
composer dumpauto

Categories