Call to a member function increment() on null - laravel

everything work fine when i call post use $id,
since i change to $slug, it show error
Symfony \ Component \ Debug \ Exception \ FatalThrowableError
(E_ERROR) Call to a member function increment() on null
my controller after i change $id to slug
public function showpost($slug)
{
$post = Post::published()
->where('slug', '=', $slug)->first();
$post->increment('view_count');
return view("blog.showpost", compact('post'));
}
here is blade file
<div class="block-heading-1">
<span class="text-muted mb-3 mt-5">
<i class="fa fa-clock-o fa-lg"></i>&nbsp{{ $post->date }}
<i class="fa fa-eye fa-lg"></i>{{ $post->view_count }}
<i class="fa fa-comments-o fa-lg"></i>&nbsp{{ $post->comments->count() }}
</span>
<h1 class="mb-4" style="font-size: 20px; padding-top: 15px; margin-bottom: 0px; pad">
{{ $post->title }}
</h1>
</div>
how to fix it?

if slug is not exist eloquent return null so when post is null, you do not increment on null model. Please be sure slug is exist.

Related

laravel middleware didn't get error codes or session messages in blade

There is page where i submit id and then middleware checks if it's right and the redirects to another route. Middleware works good but, i can't get messages in my blades.
middleware:
public function handle($request, Closure $next)
{
$exists =Kuponas::where('id', $request->id)->exists();
if (!$exists) {
return \Redirect::to(url('/'))->with('pin','Duomenys neteisingi, patikrinkite ');
}
return $next($request);
}
Blade:
#error('pin')
<p>
<i><b>Error:</b> {{ $message }}</i>
</p>
#enderror
or
#if ($message = Session::get('pin'))
<div class="alert alert-success alert-block"
style="position:relative;left:260px;width: 50%;text-align: center;">
<button type="button" style="position:relative; bottom: 5px; color: white;" s="close"
data-dismiss="alert">×</button>
<strong style="color: white;">{{ $message }}</strong>
</div>
#endif
Doesn't work either if I enter bad value in input.
Try this, Blade:
#if(session('pin'))
<p>
<i><b>Error:</b> {{ $message }}</i>
</p>
#endif

"Undefined offset: 1" error in Laravel. What is going on?

I´m trying to pass in my view all posts I have in my database with a foreach, but this error pops up.
Here is my view:
<ul>
{{ <li>#foreach ($posts => $posts) }}
<div class="row section scrollspy" style="padding:10px; margin-top:10px;">
<div class="content-box col s12" style="padding:20px; margin-top:40px; background: #f2f2f2; border-radius:10px;">
<div class="i_title" style="text-align:center; margin: -57px 0 0 0;">
<img class="responsive-img circle" src="images/profile_picture.jpg" style="width:60px; box-shadow: 0 6px 10px 0 rgba(0, 0, 0, 0.2);"><span class="tooltiptext">#Username{{ $user->username }}</span>
</div>
<p class="col s12"{{ $post->post }}</p>
</div>
</div>
{{ #endforeach</li> }}
</ul>
My Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function getUsers()
{
$user = DB::table('users')->get();
return view('layouts/welcomeView', ['users' => $user]);
}
public function getPosts()
{
$posts = DB::table('posts')->get();
return view('layouts/welcomeView', ['posts' => $posts]);
}
}
My database have some posts, so thats not the problem. I think that the trouble is that I´m not passing well the variable with the posts. What can I do??
A couple of things wrong with this.
Firstly, you're mixing blade directives up. {{ }} is used to echo something out. Whatever is inside {{ and }} is interpreted as PHP and is passed into a function to do some escaping and it is echoed out. So when you're doing {{ <li>#foreach ($posts => $posts) }}, the Blade compiler tries to treat <li>#foreach ($posts => $posts) as PHP code which will result in a syntax error. The #foreach doesn't belong inside {{ }}.
Secondly, I noticed inside your #foreach that you have $posts => $posts. Notice that the variables on each side of the arrow is the same? That is no doubt a typo but it would result in the first iteration of the loop overwriting the $posts variable with the first entry and the loop would try to continue iterating over this new, single value. It's likely that this is causing the error you're seeing.
This is probably closer to what you're looking for:
<ul>
#foreach ($posts => $post)
<li>
<div class="row section scrollspy" style="padding:10px; margin-top:10px;">
<div class="content-box col s12" style="padding:20px; margin-top:40px; background: #f2f2f2; border-radius:10px;">
<div class="i_title" style="text-align:center; margin: -57px 0 0 0;">
<img class="responsive-img circle" src="images/profile_picture.jpg" style="width:60px; box-shadow: 0 6px 10px 0 rgba(0, 0, 0, 0.2);"><span class="tooltiptext">#Username{{ $user->username }}</span>
</div>
<p class="col s12"{{ $post->post }}</p>
</div>
</div>
</li>
#endforeach
</ul>
Change your view to;
<ul>
<li>
#foreach ($posts => $post)
<div class="row section scrollspy" style="padding:10px; margin-top:10px;">
<div class="content-box col s12" style="padding:20px; margin-top:40px; background: #f2f2f2; border-radius:10px;">
<div class="i_title" style="text-align:center; margin: -57px 0 0 0;">
<img class="responsive-img circle" src="images/profile_picture.jpg" style="width:60px; box-shadow: 0 6px 10px 0 rgba(0, 0, 0, 0.2);"><span class="tooltiptext">#Username{{ $user->username }}</span>
</div>
<p class="col s12"{{ $post->post }}</p>
</div>
</div>
#endforeach
</li>
</ul>
You might need to move #Username if that isn't defined somewhere.
It is generally good practice to check there is something in an array before you foreach it.
You can achieve this by doing;
#if(! $posts->isEmpty())
#foreach ($posts => $post)
....
#endforeach
#endif

"Property does not exist on this collection instance" error while joining in laravel 5.4

UserAcademyController.php
public function view_video()
{
$materialList = DB::table('material')
->join('material_group', 'material.group_id', '=', 'material_group.id')
->select('material.*', 'material_group.group_thumbnail_url')
->get();
return view('user-academy.view_video', ['materialList' => $materialList]);
}
view_video.blade.php
#foreach ($materialList as $material)
<div class="col-sm-6 col-lg-4 col-md-4">
<div class="thumbnail">
<a href="{!! url('user-academy/view/' . $material->id)!!}">
#if($material->thumbnail_url !== null)
<img src="{{$material->thumbnail_url}}"
style="width: 700px; height: 300px">
#elseif($materialList->group_thumbnail_url !== null)
<img src="{{$materialList->group_thumbnail_url}}"
style="width: 700px; height: 300px">
#elseif($material->thumbnail_url !== null && $materialList->group_thumbnail_url !== null)
<img src="http://www.independentmediators.co.uk/wp-content/uploads/2016/02/placeholder-image.jpg"
style="width: 700px; height: 300px">
#endif
</a>
<div class="caption">
<h4 class="pull-right text-success">${{$material->price}} </h4>
<h4>
{{ $material->title }}
</h4>
<hr>
<p class="description">{!! $material->description !!} </p>
</div>
</div>
</div>
#endforeach
This is the "material" table
This is the "material_group" table
I get this error even though I copied everything exactly from laravel documentations and followed many videos on this topic I am a new programmer so this may be a very obvious mistake but I have spent a fair share of time looking at the code and just cannot find where the error is!
You are trying to access group_thumbnail_url property on Collection class which is for sure not exist, that's why you got that error.
the solution is to replace $materialList->group_thumbnail_url by material->group_thumbnail_url

method links does not exist - laravel 5.4

I am using filter by serial number in table,, but when I click the button error like this
" method links does not exist"
this is my controller
public function show(Request $request)
{
$instrument = Instrument::when($request->serial_number, function ($query) use ($request) {
$query->where('serial_number', 'like', "%{$request->serial_number}%");
})->paginate(5);
$instrument->appends($request->only('serial_number'));
return view('settinginstrument.index', compact('settinginstrument'));
}
this is my blade:
<table class="table">
#foreach ($instruments as $instrument)
<tr>
<td>
Serial Number : {{ $instrument->serial_number }}
#if($instrument->customer !== NULL)
<div class="text-muted"><i class="fa fa-hospital-o" aria-hidden="true"></i> {{ $instrument->customer->name }}</div>
#endif
#if($instrument->contractType !== NULL)
<div class="text-muted"><i class="fa fa-compress" aria-hidden="true"></i> {{ $instrument->contractType->name }}</div>
#endif
</td>
<td>
<div class="pull-right">
<a type="button" href="{{ route('instrument.edit', ['instrumentType' => $instrumentType->id, 'instrument' => $instrument->id]) }}"
class="btn btn-success ">
<i class="fa fa-pencil"></i> Edit
</a>
#if($instrument->customer == NULL || $instrument->contractType == NULL)
<a href="{{ route('instrument.destroy', ['instrumentType' => $instrumentType->id, 'instrument' => $instrument->id]) }}"
data-method="delete" data-confirm="" class="btn btn-danger">
<i class="fa fa-trash"></i> <span class="hidden-xs">Delete</span>
</a>
#endif
</div>
</td>
</tr>
#endforeach
</table>
<div class="paginator text-center">{{ $instruments->links() }}</div>
#else
....................................
where wrong with my code?
You are not passing the param to the view:
public function show(Request $request)
{
$instruments = Instrument::when($request->serial_number, function ($query) use ($request) {
$query->where('serial_number', 'like', "%{$request->serial_number}%");
})->paginate(5);
$instrument->appends($request->only('serial_number'));
return view('settinginstrument.index',['instruments' => $instruments);
}
Then on the blade:
{{$instruments->links()}}
When you have zero counts of record and you are trying to access the links() then such issue occurs
Add on condition to check the record exists.
#if($instruments)
<div class="paginator text-center">{{ $instruments->links() }}</div>
#endif
Also in the controller you have one typo error $instruments and $instrument
I recommend that add the condition above the foreach
and on blank result show some message that record not found.
Update
Also pass the $instruments to the balde
$instruments = Instrument::when($request->serial_number, function ($query) use ($request) {
$query->where('serial_number', 'like', "%{$request->serial_number}%");
})->paginate(5);
$instruments->appends($request->only('serial_number'));
return view('settinginstrument.index', compact('instruments'));

laravel 5.4 pagination issue invalid argument supplied for foreach()

I have around 50 objects in an array.
$user = User::with('abc','def','ghi','jkl','mno','pqr')
->where([['id', '<>', Auth::user()->id],['role', '<>', 2]])->simplePaginate(15);
$users = json_decode($user,true);
Have I placed ->simplePaginate(15) this correctly? Can I do json_decode after that? like I am doing? I dont get any error in controller.
In Views
#section('content')
<div class="container-fluid">
<div></br></br></div>
#include('errors.list')
<div class="row">
#foreach($users as $user)
<a href="#" onclick=document.getElementById('{{$user->id}}').style.display='block'>
<div class="col-md-3" style="margin-bottom:50px;">
#if($user["search_status"] == 'matched')
<div class="w3-card-12-disabled" style="border-radius:15px;width:225px; padding-top: 20px; background-color: #FFA534;">
#else
<div class="w3-card-12" style="border-radius:15px;width:225px; padding-top: 20px; background-color: #FFA534;">
#endif
<img align="center" src="{{$user->photo}}" style=" border-radius:50%; ; border-style: solid; border-color: #333; border-width: 5px; margin-left:15%;" width="150px !important" height="150px !important" />
<h3 style="color:#000;
padding-top: 20px;" align="center">{{ $user->firstname}}</br>{{ $user->lastname}}</h3>
<div style="display:flex; justify-content: center;">
<div class="tooltip2">
<img align="middle" style="" src="{{$user->natives->flag}}"/>
<span class="tooltiptext">{{$user->natives->language}}</span>
</div>
</div>
</br>
</div>
</div>
</a>
#endforeach
<div class="row">
#foreach($users as $user)
<div id="{{$user->id}}" class="w3-modal">
<div class="w3-modal-content w3-animate-top w3-card-8">
<div id="div1" style="padding:40px 30px 30px 30px;">
<img style="border-radius:50%; border:5px solid #333; margin-left:18px" src="{{$user->photo}}" width="200px !important" height="200px !important">
<div style="text-align: center; padding-top:70px;">
{!! Form::open(['url' => '/users/'. $user->id.'/reportc']) !!}
{!! Form::hidden('_method', 'POST') !!}
{!! Form::hidden('friend', $user->id, null, ['class'=>'form-control']) !!}
{!! Form::submit('Report', ['class'=>'btn', 'style' => 'padding: 10px 10px 10px 10px; color:#000; border-color:#000;']) !!}
{!! Form::close() !!}
</div>
</div>
<div id="div2" style="padding:40px 0px 40px 0px;">
<span onclick=document.getElementById('{{$user->id}}').style.display='none'
class="w3-closebtn">×</span>
<h1>{{ $user->firstname}} {{ $user->lastname}}</h1>
</br>
</br>
<h5 style="padding-top:30px;"><b>About Me:</b> {{ $user->bio}} </h5>
<h5 style="padding-top:10px;"><b>Campus:</b> {{$user->campus->campus_name}}</h5>
<h5 style="padding-top:10px;"><b>School:</b> {{ $user->schools->schools_name}} </h5>
<h5 style="padding-top:10px;"><b>Year:</b> {{ $user->years->years_name}} </h5>
<h5 style="padding-top:10px;"><b>Native Speaker of:</b> {{$user->natives->language}} </h5>
<h5 style="padding-top:10px;"><b>Second Native Speaker of:</b> {{ $user->snatives->language }} </h5>
<h5 style="padding-top:10px;"><b>Seeking Speaker of:</b>
#foreach($seeks as $seek)
#if($seek->user_id === $user->id)
{{ $seek->language}},
#endif
#endforeach </h5>
</div>
</div>
</div>
#endforeach
</div>
{!! $users->links() !!}
</div>
</div>
#endsection
Even if I dont put this code {{ $users->links() }} in view I still get same error. I guess issue is with the pagination code on controller.
Edited
I have this small issue still:
Before
<h5 style="padding-top:10px;"><b>Campus:</b> {{$user['campus']['campus_name']}}</h5>
<h5 style="padding-top:10px;"><b>School:</b> {{ $user['schools']['schools_name']}} </h5>
<h5 style="padding-top:10px;"><b>Year:</b> {{ $user['years']['years_name']}} </h5>
<h5 style="padding-top:10px;"><b>Native Speaker of:</b> {{$user['natives']['language']}} </h5>
<h5 style="padding-top:10px;"><b>Second Native Speaker of:</b> {{$user['snatives']['language']}} </h5>
<h5 style="padding-top:10px;"><b>Seeking Speaker of:</b>
#foreach($seeks as $seek)
#if($seek->user_id === $user['id'])
{{ $seek->language}},
#endif
#endforeach </h5>
After
<h5 style="padding-top:10px;"><b>Campus:</b> {{$user->campus->campus_name}}</h5>
<h5 style="padding-top:10px;"><b>School:</b> {{ $user->schools->schools_name}} </h5>
<h5 style="padding-top:10px;"><b>Year:</b> {{ $user->years->years_name}} </h5>
<h5 style="padding-top:10px;"><b>Native Speaker of:</b> {{$user->natives->language}} </h5>
<h5 style="padding-top:10px;"><b>Second Native Speaker of:</b> {{$user->snatives->language}} </h5>
<h5 style="padding-top:10px;"><b>Seeking Speaker of:</b>
#foreach($seeks as $seek)
#if($seek->user_id === $user->id)
{{ $seek->language}},
#endif
#endforeach </h5>
This gives After code gives me error trying to get property of non-object which is why I was using json_decode() and Before code. How do I fix these?
result
{
"per_page":12,
"current_page":1,
"next_page_url":"http:\/\/localhost:8000\/users\/community?page=2",
"prev_page_url":null,
"from":1,
"to":12,
"data":[
{
"id":5,
"firstname":"Beth",
"lastname":"Hanley",
"email":"bah3#org.uk",
"role":1,
"photo":"uploads\/2.jpg",
"bio":"Hockey fan, foodie, gamer, Saul Bass fan and HTML5 Guru.",
"campus":{
"id":1,
"campus_name":"name"
},
"school":"1",
"year":"1",
"native_lang":"2",
"native_lang_flag":"2",
"search_status":"available",
"created_at":null,
"updated_at":null,
"lastlogin":null,
"verification_code":null,
"isverify":"0",
"native_lang_2":null,
"native_lang_flag_2":null,
"schools":{
"id":1,
"schools_name":"School of Energy, Geoscience, Infrastructure and Society"
},
"years":{
"id":1,
"years_name":"First"
},
"flags":{
"id":2,
"name":"\u00c5land Islands",
"flag":"\/flags\/AX-32.png"
},
"natives":{
"id":2,
"language":"English",
"flag":"\/flags\/GB-32.png"
},
"snatives":null
},
User Model
public function friends()
{
return $this->hasMany('App\Friend','friend_id','id');
}
public function seeks()
{
return $this->belongsToMany('App\Language');
}
public function natives()
{
return $this->hasOne('App\Language','id','native_lang');
}
public function snatives()
{
return $this->hasOne('App\Language','id','native_lang_2');
}
public function roles()
{
return $this->hasOne('App\Role','id','role');
}
public function campus()
{
return $this->hasOne('App\Campus','id','campus');
}
public function schools()
{
return $this->hasOne('App\School','id','school');
}
public function years()
{
return $this->hasOne('App\Year','id','year');
}
public function flags()
{
return $this->hasOne('App\Flag','id','native_lang_flag');
}
Campus Model
public function users()
{
return $this->belongsTo('App\User','campus','id');
}
Year Model
public function users()
{
return $this->belongsTo('App\User','year','id');
}
You don't need to json encode anything and access the object property directly.
Controller
$users = User::with('abc','def','ghi','jkl','mno','pqr')
->where([
['id', '<>', auth()->id()],
['role', '<>', 2]
])->simplePaginate(15);
return view('someview', compact('users'));
View
<div class="row">
#foreach($users as $user)
<a href="#" onclick="document.getElementById('{{ $user->id }}').style.display='block'">
<div class="col-md-3" style="margin-bottom:50px;">
#if($user->search_status == 'matched')
<div class="w3-card-12-disabled"
style="border-radius:15px;width:225px; padding-top: 20px; background-color: #FFA534;">
#else
<div class="w3-card-12"
style="border-radius:15px;width:225px; padding-top: 20px; background-color: #FFA534;">
#endif
<img align="center" src="{{ $user->photo }}"
style=" border-radius:50%; ; border-style: solid; border-color: #333; border-width: 5px; margin-left:15%;"
width="150px !important" height="150px !important"/>
<h3 style="color:#000;
padding-top: 20px;" align="center">{{ $user->firstname }}<br/>{{ $user->lastname}}</h3>
<br/>
</div>
</div>
</div>
</a>
#endforeach
</div>
{!! $users->links() !!}

Resources