I'm still learning so forgive me if this is a stupid question but I can't seem to find a fix for it myself.
I am having trouble getting the "title" property of the JSON and from the error that I got
"Trying to get property 'tag' of non-object pages/results.blade.php:28"
I understand that $tags is an array not an object.
I did a foreach with $tags with
foreach ($result->tags as $tag)
I also know that $tag contains the data I need because when I die and dump $tag I get this
My question is how do I access an unnamed JSON that is inside an array?
The title property is inside the "tags" array and the browser is giving me an error that I can't access it because it's a non-object.
Can you please help me with the code?
Here is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use GuzzleHttp\Client;
class PageController extends Controller
{
// public function __construct() {
// $this->middleware('auth');
// }
public function index() {
$user = Auth::user();
return view('pages/home', compact('user'));
}
public function result(Request $request) {
// https://api.unsplash.com/search/photos?query=philippines&client_id=hb-UQIJ2DMaPckaJOO5nxrC90uYnaVRGTMz3S8WHzJY
$input = $request->input('query');
$client = new Client();
// var_dump($input); die;
// dd($input);
// var_dump($request->input('query')); die;
$res = $client->request('GET', "https://api.unsplash.com/search/photos", [
"query" => [
"query" => $input,
"client_id" =>"hb-UQIJ2DMaPckaJOO5nxrC90uYnaVRGTMz3S8WHzJY",
"per_page" => 100
]
]);
$data = $res->getBody();
$data = json_decode($data);
$filteredData = [];
// return $data->results;
foreach($data->results as $result) {
$urls = $result->urls;
array_push($filteredData,$result);
foreach ($result->tags as $tag) {
$tags = $result->tags;
array_push($filteredData, $tag);
// dd($tag);
foreach($tag as $key => $value) {
if($key === 'title') {
array_push($filteredData,$value);
array_push($filteredData,$key);
// dd($filteredData);
}
}
}
$user = Auth::user();
return view('pages/results', compact('user', 'filteredData', 'input'));
}
}
Here is my blade
#extends('layouts/main')
#section('title')
Design Storm - Inspiration for Developers
#endsection
#section('content')
<div id="site-section">
<div class="container">
<div id="results">
<div>
<div class="search-container">
<form action="/results" method="POST">
#csrf
<input class="search" type="text" value="{{$input}}" placeholder="Search" name="query">
</form>
</div>
<div class="boxes">
<div class="row">
#foreach ($filteredData as $result)
<div class="col-md-3">
<div class="box">
<div style="position: relative; background: url('{{$result->urls->small}}') no-repeat center center;-webkit-background-size: cover;-moz-background-size: cover;-o-background-size: cover;background-size: cover; height: 200px;">
<div class="add-btn "><i class="fa fa-check" aria-hidden="true"></i></div>
</div>
#foreach ($filteredData as $tag)
<h4>
{{$filteredData->tag->title}}
</h4>
#endforeach
</div>
</div>
#endforeach
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
"
Related
So this function is supposed to add the product into a cart, but i've been getting the error
Too few arguments to function
App\Http\Controllers\Shop\CartController::addToCart(), 0 passed in
C:\xampp\htdocs\nerdS\vendor\laravel\framework\src\Illuminate\Routing\Controller.php
on line 54 and exactly 1 expected
I tried changing key words here and there on my controller, but nothing seems to do it. This is the the controller:
<?php
namespace App\Http\Controllers\Shop;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
Use App\Models\Product;
Use App\Models\Order;
class CartController extends Controller {
public function placeOrder() {
if(session('id')){
if(\Cart::count()){
\App\Models\Order::store();
return redirect('shop')->with('status', 'Thank you for buying!');
}
return redirect('cart');
}
session(['place-order-process' => true]);
return redirect('login')->with('status', 'To complete your order, please log in. Not a member yet? Join the club! ');
}
public function deleteCart() {
\Cart::destroy();
return redirect('shop')->with('status', 'The cart is now empty.');
}
public function deleteItem($rowId) {
\Cart::remove($rowId);
return redirect('cart')->with('status', 'The item was deleted.');
}
public function updateCart(Request $request){
\Cart::update($request->rowId, $request->quantity);
$data = [
'cart_count' =>\Cart::count(),
'cart_total' => \Cart::total(),
'product_total' => \Cart::get($request->rowId)->total(),
];
return json_encode($data);
}
public function displayCart() {
\Cart::setGlobalTax(0);
$data['items'] = \Cart::content();
$data['total'] = \Cart::total();
return view('cart.cart', $data);
}
public function addToCartByQty (Request $request){
\App\Models\Product::addToCart($request->id, (int) $request->quantity);
return \Cart::count();
}
public function addToCart ($id){
\App\Models\Product::addToCart($id);
return \Cart::count();
}
}
My model for products:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
class Product extends Model {
public function category() {
return $this->belongsTo('App\Models\Category');
}
public static function deleteProduct($id){
$product = self::findOrFail($id);
Storage::disk('public')->delete($product->image);
self::destroy($id);
}
public static function editProduct($request){
$product = self::findOrFail($request->product);
$product->name = $request->name;
$product->slug = $request->slug;
$product->price = $request->price;
$product->description = $request->description;
$product->category_id = $request->category;
if ($request->image){
Storage::disk('public')->delete($product->image);
$product->image = $request->image->store('images/products', 'public');
}
$product->save();
}
public static function getProductById($id){
return self::finOrFail($id);
}
public static function store($request){
$product = new self();
$product->name = $request->name;
$product->slug = $request->slug;
$product->price = $request->price;
$product->description = $request->description;
$product->category_id = $request->category;
$product->image = $request->image->store('images/products', 'public');
$product->save();
}
public static function getAll(){
return self::orderBy('slug')->get();
}
public static function addToCart($id, $qty = 1){
$product = self::findOrFail($id);
\Cart::add([
'id' => $product->id,
'name' => $product->name,
'qty' => $qty,
'price' => $product->price,
'weight' => 0
]);
}
public static function getProduct($cat, $pro){
$product = self::where('slug', $pro)->firstOrFail();
$product_cat = $product->category->slug;
//retun ($product_cat === $cat) ? $product_cat: false;
abort_if($product_cat !== $cat, 404);
return $product;
}
//use HasFactory;
}
The page view:
#extends('template')
#section('content')
<div class="row">
<div class="col-md-7">
<h1> {{$product->name}} </h1>
<p>{{$product->descriprion}}</p>
<p> Only for: ₪ {{$product->price}}</p>
<form id="add-to-cart" method="post" action="{{url('add-to-cart')}}">
#csrf
<div class="number">
<span class="minus"> - </span>
<input type="text" value="1" readonly/>
<span class="plus"> + </span>
<input type="hidden" value="{{$product->id}}">
<button class="btn btn-primary" type="submit"> Add </button>
</div>
</form>
<div class="col-md-5">
<img src="{{asset('storage/' . $product->image)}}">
</div>
</div>
</div>
#endsection
and my route:
Route::get('add-to-cart/{product_id}', 'App\Http\Controllers\Shop\CartController#addToCart');
You need to pass the $product->id in the form action's url(). That route parameter needs to be there so that it is received in the addToCart method in controller
#extends('template')
#section('content')
<div class="row">
<div class="col-md-7">
<h1> {{$product->name}} </h1>
<p>{{$product->descriprion}}</p>
<p> Only for: ₪ {{$product->price}}</p>
<form id="add-to-cart" method="post" action="{{url('add-to-cart/' . $product->id)}}">
#csrf
<div class="number">
<span class="minus"> - </span>
<input type="text" value="1" readonly/>
<span class="plus"> + </span>
<input type="hidden" value="{{$product->id}}">
<button class="btn btn-primary" type="submit"> Add </button>
</div>
</form>
<div class="col-md-5">
<img src="{{asset('storage/' . $product->image)}}">
</div>
</div>
</div>
#endsection
And you have declared your route as get instead of post. Following restful conventions your route should be declared as a post route
Route::post('add-to-cart/{product_id}', 'App\Http\Controllers\Shop\CartController#addToCart');
There is a mismatch in your route (Route::get('add-to-cart/{product_id}) and the parameter passed in your function addToCart ($id)
Had u provide product_id in route (add-to-cart/{product_id})?
Since you are using a GET route vs POST, you have to change your form method from POST to GET and also pass the id in the action url -
<form id="add-to-cart" method="get" action="{{url('add-to-cart/' . $product->id)}}">
Change your definition of addToCart method in CartController as following.
public function addToCart (Request $request, $id)
{
\App\Models\Product::addToCart($id);
return \Cart::count();
}
In Laravel 7, I am have a task management app. I can upload tasks (posts if it were a blog) and images. I have a multiple image upload working as expected. When it comes time to delete a task, the task deletes just fine but the images are left in the database and in the disk which is public into a folder called task-images. Being new to Laravel, I am struggling on how to go about this. I tried to change the settings in the filesystem.php (which I will post with the commented out code) but that didn't change the location as I had expected. In the end, I want to be able to delete the multiple images when I delete a post and also click delete on an individual image and delete that from both db and disk. I am using resource controller for all my task routes. I have no idea how to go about this and the tutorials that I have found don't really address my specific issue. Any help would be greatly appreciated. Thank you in advance.
Here is my task controller at TaskController.php
<?php
namespace App\Http\Controllers;
use App\Task;
use App\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
class TasksController extends Controller
{
public function index()
{
$tasks = Task::orderBy('created_at', 'desc')->paginate(10);
return view('/tasks')->with('tasks', $tasks);
}
public function create()
{
return view('tasks.create');
}
public function store(Request $request)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
// Create Task
$user = Auth::user();
$task = new Task();
$data = $request->all();
$task->user_id = $user->id;
$task = $user->task()->create($data);
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->move('task-images', $name);
$task->image()->create(['name' => $name]);
$images = new Image;
$images->name = $name;
}
}
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->task_status;
$task->save();
return redirect('/home')->with('success', 'Task Created');
}
public function edit($id)
{
$task = Task::find($id);
return view('tasks.edit', ['task' => $task]);
}
public function update(Request $request, $id)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
$task = Task::find($id);
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->input('task_status');
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->move('task-images', $name);
$task->image()->create(['name' => $name]);
}
}
$task->update();
return redirect('/home')->with('success', 'Task Updated');
}
public function show($id)
{
$task = Task::find($id);
return view('tasks.show')->with('task', $task);
}
public function destroy($id)
{
$task = Task::findOrFail($id);
// $image = '/task-images/' . $task->image;
Storage::delete($task->image);
$task->delete();
return redirect('home')->with('success', 'Task Deleted');
}
}
filesystem.php (just the disks section)
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
// 'root' => public_path('task-images'),
],
...
in my individual show template, show.blade.php complete in case there is a code conflict.
#extends('layouts.master')
#section('content')
<div class="container">
Go Back
<div class="card p-3">
<div class="row">
<div class="col-md-4 col-sm-12">
<h3>Task</h3>
<p>{{ $task->task_name }}</p>
<h3>Assigned On:</h3>
<p>{{ $task->created_at->format('m/d/Y') }}</p>
<h3>Assigned To:</h3>
<p>{{ $task->task_assigned_to }}</p>
</div>
<div class="col-md-4 col-sm-12">
<h3>Task Description</h3>
<p>{{ $task->task_description }}</p>
<h3>Priority</h3>
<p>{{ $task->task_priority }}</p>
<h3>Status</h3>
<p>{{ $task->task_status }}</p>
</div>
<div class="col-md-4 col-sm-12">
<h3>Test Environment Date:</h3>
<p>{{ $task->task_to_be_completed_date }}</p>
<h3>Notes</h3>
<p>{{ $task->task_notes }}</p>
<h3>Action</h3>
<div style="display: inline;">
<a href="/tasks/{{$task->id}}/edit" class="btn btn-sm btn-primary mr-2">
<i class="fa fa-edit"></i> Edit
</a>
</div>
<form style="display: inline;" action="/tasks/{{ $task->id }}" method="POST" class="">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm ml-1 mr-1">
<i class="fa fa-trash"></i> Delete
</button>
</form>
</div>
<div class="col-md-12">
<h5>Images</h5>
<hr />
<div class="row">
#if($task->image->count()>0)
#for($i=0; $i < count($images = $task->image()->get()); $i++)
<div class="col-lg-4 col-md-6 col-sm-12">
<img class="w-50 mb-2" src="/task-images/{{ $images[$i]['name'] }}" alt="">
<form style="display: inline;" action="/tasks/{{ $task->name }}" method="POST" class="">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm ml-1 mr-1">
<i class="fa fa-trash"></i> Delete
</button>
</form>
</div>
#endfor
#else
<p>No images found</p>
#endif
</div>
<br />
</div>
</div>
</div>
</div>
<!--Modal Start-->
<div id="lightbox" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog">
<button type="button" class="close hidden" data-dismiss="modal" aria-hidden="true">×</button>
<div class="modal-content">
<div class="modal-body">
<img class="w-100" src="" alt="" />
</div>
</div>
</div>
</div>
<!--Modal End-->
#endsection
#section('scripts')
<script>
$(document).ready(function() {
var $lightbox = $('#lightbox');
$('[data-target="#lightbox"]').on('click', function(event) {
var $img = $(this).find('img'),
src = $img.attr('src'),
alt = $img.attr('alt'),
css = {
'maxWidth': $(window).width() - 100,
'maxHeight': $(window).height() - 100
};
$lightbox.find('.close').addClass('hidden');
$lightbox.find('img').attr('src', src);
$lightbox.find('img').attr('alt', alt);
$lightbox.find('img').css(css);
});
$lightbox.on('shown.bs.modal', function (e) {
var $img = $lightbox.find('img');
$lightbox.find('.modal-dialog').css({'width': $img.width()});
$lightbox.find('.close').removeClass('hidden');
});
});
</script>
#endsection
In my Task model, Task.php, I have:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Image;
class Task extends Model
{
protected $fillable = [
'task_name', 'task_priority', 'task_assigned_to', 'task_assigned_by', 'task_description', 'task_to_be_completed_date', 'task_status',
'task_notes'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function image()
{
// return $this->hasMany('App\Image');
return $this->hasMany(Image::class);
}
}
and finally my Image Model Image.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Task;
class Image extends Model
{
protected $fillable = [
'task_id',
'name',
];
protected $uploads = '/task-images/';
public function getFileAttribute($image)
{
return $this->uploads . $image;
}
public function task()
{
// return $this->belongsTo('App\Task', 'task_id');
return $this->belongsTo(Task::class);
}
}
If I am missing something, please let me know so I can edit my question. Again, thank you in advance for helping me with this issue. I have been scratching my head all week on this one. Cheers.
Edit
After implementing boot functions in my model as suggested below, I received an error that an invalid argument was used for foreach. I ran a dd($task); and the following image shows the result.
Final Edit
The answer below worked for my situation. I did have to edit some things to finalize the resolution:
in Task.php I changed the foreach to the following.
foreach($task->image ?: [] as $image)
I had declared image and not image in my model and that was causing a problem. Adding the ternary operator also helped the code not throw any errors.
In my TasksController.php I changed both the update and create functions with the same ternary operator as follows:
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files ?: [] as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->move('task-images', $name);
$task->image()->create(['name' => $name]);
}
}
I hope this helps anyone else having the same issue. Thanks to #GrumpyCrouton and #lagbox for their help in resolving this as well as #user3563950
Without them, I would still by stratching my head for another couple of weeks.
on your App\Image class, implement to boot function with the following;
use Illuminate\Support\Facades\Storage;
public static function boot() {
parent::boot();
self::deleting(function($image) {
Storage::delete(Storage::path($image->name));
});
}
Also implement the boot method in App\Task class
use Illuminate\Support\Facades\Storage;
public static function boot() {
parent::boot();
self::deleting(function($task) {
foreach($task->images as $image) {
$image->delete();
}
});
}
Now on your TaskController implement the destroy method as follows;
public function destroy($id)
{
$task = Task::findOrFail($id);
$task->delete();
return redirect('home')->with('success', 'Task Deleted');
}
As a bonus, learn Laravel model binding to ease the pain of finding an instance using findOrFail()
Question
Why my variable in ProfileController is not loaded in my blade(index2.blade.php)?
Error Message
Undefined variable: plus (View: /work/resources/views/stories/index2.blade.php)
My Codes
routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('login');
Route::match(['get','post','middleweare'=>'auth'], '/',
'StoriesController#index',
'StoriesController#store',
'ProfileController#index',
'ProfileController#store'
);
Route::match(['get','post','middleweare'=>'auth'], 'stories/create',
'StoriesController#add',
'StoriesController#upload'
);
Route::match(['get','post','middleweare'=>'auth'], 'profile/create',
'ProfileController#add',
'ProfileController#upload'
);
Route::group(['middleweare' => 'auth','name'=>'profile'], function () {
Route::get('/profile/edit', 'ProfileController#edit');
});
Route::get('/home', 'HomeController#index')->name('home');
Auth::routes();
app/Http/Controllers/ProfileController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\stories;
use App\History;
use App\Posts;
use Carbon\Carbon;
use Storage;
class ProfileController extends Controller
{
public function index(Request $request)
{
$plus = Posts::all();
return view('stories.index2', compact('plus'));
}
public function upload(Request $request)
{
$this->validate($request, [
'file' => [
'required',
'file',
'image',
'mimes:jpeg,png',
]
]);
if ($request->file('file')->isValid([])) {
$path = $request->file->store('public');
return view('stories.index2')->with('filename', basename($path));
} else {
return redirect()
->back()
->withInput()
->withErrors();
}
}
public function store(Request $request)
{
$d = new \DateTime();
$d->setTimeZone(new \DateTimeZone('Asia/Tokyo'));
$dir = $d->format('Y/m');
$path = sprintf('public/posts/%s', $dir);
$data = $request->except('_token');
foreach ($data['plus'] as $k => $v) {
$filename = '';
$posts = Posts::take(1)->orderBy('id', 'desc')->get();
foreach ($posts as $post) {
$filename = $post->id + 1 . '_' . $v->getClientOriginalName();
}
unset($post);
if ($filename == false) {
$filename = 1 . '_' . $v->getClientOriginalName();
}
$v->storeAs($path, $filename);
$post_data = [
'path' => sprintf('posts/%s/', $dir),
'name' => $filename
];
$a = new Posts();
$a->fill($post_data)->save();
}
unset($k, $v);
return redirect('/');
}
public function create(Request $request)
{
$this->validate($request, Profile::$rules);
$profile = new Profile;
$form = $request->all();
unset($form['_token']);
$profile->fill($form);
$profile->save();
return redirect('/');
}
public function add()
{
return view('profile.create2');
}
public function edit()
{
return view('profile.edit');
}
}
resources/views/stories/index2.blade.php
#extends('layouts.front2')
#section('title','mainpage')
#section('content')
<div class="profile">
<div class="profileimg">
#foreach ($plus as $pplus)
<img src="/storage/{{ $pplus->path . $pplus->name }}" style="height: 210px; width: 210px; border-radius: 50%;">
#endforeach
</div>
<div class="name">
#guest
<a class="nav-link2" href="{{ route('register')}}">{{ __('Create Accout!')}}</a>
#else
<a id="navbarDropdown" class="nav-link2" href="#" role="button">
{{Auth::user()->name}}<span class="caret"></span></a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
#csrf
</form>
</div>
#endguest
<div class="aboutme">
You can write your profile here!You can write your profile here!You can write your profile here!
You can write your profile here!You can write your profile here!You can write your profile here!
You can write your profile here!You can write your profile here!You can write your profile here!
You can write your profile here!You can write your profile here!You can write your profile here!
You can write your profile here!You can write your profile here!You can write your profile here!
</div>
</div>
<div class="new">
<div class="newtitle">
<h1>New</h1>
</div>
<div class="container1">
#foreach ($plus as $pplus)
<img src="/storage/{{ $pplus->path . $pplus->name }}" class="images" style="height: 150px; width: 150px; border-radius: 50%;">
#endforeach
<div class="more">
more...
</div>
</div>
</div>
<div class="stories">
<div class="titlestories">
<h1>Stories</h1>
</div>
<div class="container2">
<div class="titleclose">
<h2>#CloseFriends</h2>
</div>
<div class="titlefollow">
<h2>#Follows</h2>
</div>
</div>
</div>
{{ csrf_field() }}
#endsection
In your upload method, you're missing the $plus variable
Change it to this
public function upload(Request $request)
{
$this->validate($request, [
'file' => [
'required',
'file',
'image',
'mimes:jpeg,png',
]
]);
if ($request->file('file')->isValid([])) {
$path = $request->file->store('public');
$filename = basename($path);
$plus = Posts::all();
return view('stories.index2', compact('filename','plus'));
} else {
return redirect()
->back()
->withInput()
->withErrors();
}
}
return view('stories.index2, [ 'plus' => Posts::all() ]); should work.
Okay i'm trying get "likes" and "users" in Posts by relationship hasOne.
here is my Post.php Model
class Posts extends Model
{
protected $table = 'posts';
public function User()
{
return $this->hasOne(User::class, 'id', 'user_id');
}
public function Like()
{
return $this->hasOne(Like::class, 'post_id', 'id');
}}
My Blade template
#foreach ($showdeals as $deal)
<div class="tab-pane active" id="home" role="tabpanel">
<div class="card-body">
<div class="profiletimeline">
{{$deal->like->status}}
<br>
{{$deal->user->email}}
<div class="sl-item">
<div class="sl-left"> <img src=" {{asset( '/assets/images/users/2.jpg')}}" alt="user" class="img-circle"> </div>
<div class="sl-right">
<div> {{$deal->user->username}} || {{$deal->subject}} <Br> <span class="sl-date">{{$deal->created_at}}</span>
<div class="m-t-20 row">
<div class="col-md-3 col-xs-12"><img src="{{$deal->image}}" alt="user" class="img-responsive radius"></div>
<div class="col-md-9 col-xs-12">
<p> {{$deal->body}} </p> עבור למוצר </div>
</div>
<div class="like-comm m-t-20"> 2 תגובות <i class="fa fa-heart text-danger"></i> 5 לייקים </div>
</div>
</div>
</div>
</div>
<hr></div>
</div>
#endforeach
And there is my Controller
class PostsController extends Controller
{
public function showdeals()
{
$showdeals = Posts::with( 'User', 'Like')->get();
return view('posts.show', compact('showdeals'));
}
public function helpnewview(){
return view('posts.anew');
}
public function helpnew(Request $request){
//User pick link
$userlink = $request['userlink'];
return \Redirect::route('newdeal', compact('userlink'));
}
public function new(Request $request)
{
//Emdeb user link
$link = Embed::create($request['userlink']);
$linke = $request['userlink'];
return view('posts.new', compact('link', 'userlink', 'linke'));
}
public function create(Request $request)
{
$posts = New Posts;
$posts->user_id = Auth::User()->id;
$posts->subject = $request['subject'];
$posts->body = $request['body'];
$posts->link = $request['link'];
$posts->price = $request['price'];
$posts->image = $request['image'];
$posts->tag = $request['tag'];
$posts->save();
return back();
}
}
Now if I do something like {{$deal->user->email}} its will work,
if I go to something like this {{$deal->like->status}} its does not work,
am I missing something ?
If you want multiple relationships to be eagerly loaded you need to use an array of relationships: Model::with(['rl1', 'rl2'])->get();
public function showdeals()
{
...
$showdeals = Posts::with(['User', 'Like'])->get();
...
}
EDIT:
From that json in the comments that I see, there is no attribute named status in your Like model so thats probably the root of the problem
Controller edit this code
public function showdeals()
{
$showdeals = Posts::all();
return view('posts.show', compact('showdeals'));
}
And blade file code
#foreach ($showdeals as $deal)
<div class="tab-pane active" id="home" role="tabpanel">
<div class="card-body">
<div class="profiletimeline">
{{ $deal->Like->status }}
<br>
{{ $deal->User->email }}
#endforeach
I think everything is good except
{{$deal->like->status}} {{$deal->user->email}}
Please try as
{{$deal->Like()->status}}
<br>
{{$deal->User()->email}}
>
I want to use pagination in category view. I only want to display 5 posts of that specific category which is selected using a slug.
I want pagination link in below.
This is my view:
#extends('layouts.frontend')
#section('content')
<!-- Stunning Header -->
<div class="stunning-header stunning-header-bg-lightviolet">
<div class="stunning-header-content">
<h1 class="stunning-header-title">Category:{{$category->name}}</h1>
</div>
</div>
<!-- End Stunning Header -->
<div class="container">
<div class="row medium-padding120">
<main class="main">
<div class="row">
#php
$i = 0;
#endphp
#foreach($category->posts as $post)
<div class="case-item-wrap">
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<div class="case-item" style="margin-top: 20px;">
<div class="case-item__thumb">
<img src="{{$post->featured}}" alt="our case">
</div>
<h6 class="case-item__title">{{$post->title}}</h6>
</div>
</div>
</div>
#php $i++; #endphp
#if($i % 3 == 0)
<div class="row"></div>
#endif
#endforeach
</div>
</div>
</main>
</div>
</div>
#endsection
And this is my frontendcontroller. Where I want to select Post with specific category Then display 5 number post in my view. Having problem in how to use pagination with realtionship.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Setting;
use App\Category;
use App\Post;
use App\User;
use App\Tag;
class FrontEndController extends Controller
{
public function index()
{
$title = Setting::first()->site_name;
$categories = Category::all();
$first_post = Post::latest()->first();
$second_post = Post::latest()->skip(1)->take(1)->get()->first();
$third_post = Post::latest()->skip(2)->take(1)->get()->first();
$english_11 = Category::find(1);
$blog = Category::find(3);
$settings = Setting::first();
$tags = Tag::all();
return view('index',compact('title','categories','first_post','second_post','third_post','english_11','blog','settings','tags'));
}
public function singlePost($slug)
{
$categories = Category::all();
$settings = Setting::first();
$post = Post::where('slug',$slug)->first();
$next_id = Post::where('id','>',$post->id)->min('id');
$prev_id = Post::where('id','<',$post->id)->max('id');
$next = Post::find($next_id);
$prev = Post::find($prev_id);
$tags = Tag::all();
$title = $post->title;
return view('single',compact('post','title','categories','settings','next','prev','tags'));
}
public function categories($slug)
{
$category = Category::where('slug',$slug)->first();
$categories = Category::all();
$title = $category->name;
$settings = Setting::first();
return view('category',compact('category','categories','title','settings'));
}
public function tags($slug)
{
$tag = Tag::where('slug',$slug)->first();
$categories = Category::all();
$title = $tag->tag;
$settings = Setting::first();
return view('tag',compact('tag','categories','title','settings'));
}
}