Laravel Crinsane/LaravelShoppingcart associate() doesn't work - laravel

In my Laravel I'm using this shoppingcart .
When I add one product to my shopping cart I want to have associate() with App\Product Model .
This is my code :
public function store(Request $request)
{
// store product information to Cart
Cart::add($request->id, $request->name, 1, $request->price)
->associate('App\Product');
return redirect(route('cart.index'))
->with('success_message', 'محصول با موفقیت به سبد اضافه شد');
}
But when I want to access model $item->model->id in view I get this error :
Trying to get property 'id' of non-object (View: C:\xampp\htdocs\digikala\resources\views\cart.blade.php)
Edit :
my cart view (cart.blade.php) codes :
<table border="1" class="table">
#foreach (Cart::content() as $item)
{{ $item->model->id }}
#endforeach
</table>

Finally i could solve this problem .
Everything was about $request data inside store() method .
Mistakes were in the form of adding product to cart .
I did not post the product ID correctly to the store() method .
If anyone had this problem in the future I hope to test $request first by this code :
public function store(Request $request)
{
return $request;
}

public function store(Request $request)
{
//verify the submitted product
$product = Product::where('slug', $request->input('slug'))->first();
//check if item is available
if($product === null){
return redirect()->route('cart.index')->with('error', 'Unable to add product to cart');
}
else{
Cart::add($product->id, $product->title, 1, $product->price)
->associate('App\Product');
return redirect()->route('cart.index')->with('success', 'Product added to cart');
}
return false;
}

Related

how to change url for edit in laravel

I have an edit page, I have used resource controller for it. Everytime the page redirects from edit (../members/16/edit) it continues with the edit page url (../members/16/members). [where it should only take ../members]
How can I remove/change url for edit.
Route
Route::resource('members', MemberController::class);
edit function
public function edit(Member $members,$id)
{
$members = Member::find($id);
return view('edit', compact('members'));
}
public function update(Request $request,$id)
{
$members = Member::find($id);
$members->name = $request->name;
$members->save();
return view('committee')->with('success', 'Member Updated successfully');
}
<a class="btn btn-sm btn-icon btn-success" title="Edit NewsRoom Details"
href="'.route("members.edit",[$members->id]).'"><i class="fas fa-edit"></i></a>
You should identify what you are passing example:
...
Your update method is not redirecting anywhere, it is simply loading a different view, the correct way to do it is:
public function update(Request $request,$id)
{
$members = Member::find($id);
$members->name = $request->name;
$members->save();
//return view('committee')->with('success', 'Member Updated successfully');
return redirect()->route('members.committee')->with('success', 'Member Updated successfully');
}

ErrorException thrown with message "Trying to get property 'user' of non-object

I am using relationship in my laravel project. I am trying to show my post and replies. But i keep getting this error. I've tried various solution but none of them worked. Can anyone help me?
Post model:
protected $fillable = [
'title', 'content', 'category_id' , 'slug', 'user_id',
];
public function user1()
{
return $this->belongsTo('App\User');
}
public function replies()
{
return $this->hasMany('App\Reply');
}
Reply model:
protected $fillable = ['content','user_id','posts_id'];
public function post(){
return $this->belongsTo('App\Post');
}
public function user()
{
return $this->belongsTo('App\User');
}
PostController:
public function shro($slug)
{
$pst= Post::where('slug',$slug)->first();
return view('posts.show')->with('p', $pst);
}
show.blade.php
<div class="panel panel-default">
<div class="panel-heading">
<img src="/uploads/avatars/{{ $p->user->avatar }}" alt="" width="70px" height="60px">
<span>{{ $p->user->name }}, <b>{{ $p->created_at->diffForHumans() }}</b></span></br>
</div>
$p, or $pst (confusing variable names) is null, and this is because ->first() can return null. Do you have a Post record in your database that matched slug?
Rule of thumb; never assume something exists.
Add some logic to ensure the Post exists before trying to access a property of it:
$post = Post::where("slug", $slug)->first();
if(!$post){
abort(404);
}
return view('posts.show')->with('post', $post);
// OR
$post = Post::where("slug", $slug)->findOrFail(); // or firstOrFail();
return view('posts.show')->with('post', $post);
Also, check your $post->user:
#if($post->user)
<img src="/uploads/avatars/{{ $post->user->avatar }}" width="70px" height="60px"/>
<span>{{ $post->user->name }}, <b>{{ $post->created_at->diffForHumans() }}</b></span></br>
#endif
If $post->user returns null, you'll have a similar error.
You can eager load the user with it's relative post at once by doing :
//...
$pst= Post::where('slug',$slug)->with(['user1'])->first();
//...

Laravel5.6 "Call to a member function delete() on null " , delete a row in table

I want to delete a row from table. The function I used in controller is:
public function destroy($id) {
$category = Category::find($id);
$category->delete();
return redirect()->back();
}
However it throws me an error:
Call to a member function delete() on null
When I use this code:
public function destroy($id) {
$category = Category::find($id);
dd($id);
}
It is showing the correct id i.e.
"1"
And when I use
public function destroy($id) {
$category = Category::find($id);
dd($category); // or
dd(Category::find($id);
}
I get the output
null
on the screen.
As mentioned in comments, the error you're getting is probably due to no category exists in the database for the given ID.
Then, when you try to find the category for that ID:
$category = Category::find($id);
The value of $category variable is null. Therefore, you get an error for trying to call delete() method on null. Under the hood, it would be the same as doing the following:
null->delete();
Which, doesn't work.
You could check the value of $category before trying to delete it. Or you may use a query to delete all records matching a given condition, in your case id = $id. This way:
public function destroy($id)
{
Category::where('id', $id)->delete();
return redirect('/')->back();
}
Refer to Deleting Models By Query in the Eloquent docs for details on how that works.
What worked for me is the following (I ensured that the $id was passing from the view):
public function destroy($id)
{
$vendor = Vendor::findorFail($id);
$vendor->delete():
}
for some reason when I did the following it showed null
public function destroy($id)
{
$vendor = Vendor::find($id);
$vendor->delete():
}
This is the view part:
{!! Form::open(array(
'style' => 'display: inline-block;',
'method' => 'DELETE',
'onsubmit' => "return confirm('".trans("global.app_are_you_sure")."');",
'route' => ['vendor.destroy', $vendor->vendor_id])) !!}
{!! Form::submit(trans('global.app_delete'), array('class' => 'btn btn-xs btn-danger')) !!}
{!! Form::close() !!}

Laravel 5.1, passing my ID

I'm trying to pass an ID of a past and insert it into another database.
I got a page with shows posts like this
/posts/{id}
. From there on i want to add a comment section, so i got my form set up like this:
<form method="POST" action="/posts/{{ $post->id }}/comments">
(When i inspect the code, it inserts the right id and the "{{ $posts->id }}" spot.
inside my routes.php i got the folling route:
Route::post('/posts/{post}/comments', 'CommentsController#store');
and inside CommentsController.php i got the following
public function store(Post $post)
{
Comment::create([
'body' => request('body'),
'post_id' => $post->id
]);
return back();
}
When ever i try to add a comment i get this error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id'
cannot be null
When i change my code from CommentsController.php to this:
'post_id' => "2"
it works fine (but the comment will always be added at post with ID 2)
I can't seem to find out why my id wont go trough.
Anny help with this?
Try this
public function store(Request $request, Post $post)
{
$comment= new Comment;
$comment->body = $request->body;
$comment->post_id = $post->id;
$comment->save();
return back();
}
The route model binding allows you to convert the Post ID passed into the route into the actual post object in the controller method. It may even work smoother if you use a relationship between a post and a comment, like so:
public function store(Request $request, Post $post)
{
$post->comments->create([
'body' => $request->body
]);
return back();
}
Inside post model
public function comments()
{
return $this->hasMany('App\Comment','post_id');
}

laravel 7 article argument not passed title in articles view

I am trying to make a single page of website but i cant passed argument article in view
my controller is:
public function single(Article $article)
{
$article->increment('viewCount');
$comments = $article->comments()->where('approved' , 1)->where('parent_id', 0)->latest()->with(['comments' => function($query) {$query->where('approved' , 1)->latest();}])->get();
return view('Home.articles.single' , compact('article' , 'comments'));
}
and my view is
<div class="subject_head">
<div class="subject_head--title"><h1 class="title">
{{$article->title}}
</h1>
</div>
</div>
but i cant passed article title. and my model is
protected $table='articles';
protected $casts= [
'images'=>'array'
];
protected $fillable= ['title','slug','description','body','images','tags'];
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
public function user()
{
return $this->belongsTo(User::class);
}
i passed this and while used
$article->all()
this passed all data
but when use
$article->title
this method is null
and when use
dd($article)
It has been changed.
Now you need to pass it as array ['name' => 'James']
in your case
public function single(Article $article)
{
$article->increment('viewCount');
$comments = $article->comments()->where('approved' , 1)->where('parent_id', 0)->latest()->with(['comments' => function($query) {$query->where('approved' , 1)->latest();}])->get();
return view('Home.articles.single' ,['article'=>$article,'comments'=$comments]));
}
Check it here : https://laravel.com/docs/7.x/views
i changed Route of
Route::get('/articles/{articleSlug}' , 'ArticleController#single');
Route::get('/series/{courseSlug}' , 'CourseController#single');
to
Route::get('/articles/{article:Slug}' , 'ArticleController#single');
Route::get('/series/{course:Slug}' , 'CourseController#single');
and solved problem.
thank you of all.

Resources