Trying to get property of non-object Laravel - laravel

i'm getting trouble in getting the data from foreign key
that i wanna get the information from table media
already make relation between 2 tables, but still error give me this Trying to get property of non-objectin spite of my table have data between those tables
Modal Dossier
public function media(){
return $this->belongsTo('App\Media');
}
Modal Media
public function dossier(){
return $this->hasOne('App\Dossier');
}
and that my view
i sent the variable $dossier and i did loop
i trying to get all info
#if($dossier->media)
<?php $ext=substr($dossier->media->url,-3) ;?>
<label class="med">
#if($ext=='pdf')
<i class="fa fa-file-pdf-o"></i>
#else
<i class="fa fa-file-word-o"></i>
#endif
{{$dossier->media->libelle}}
</label><a class="btn btn-warning btn-small pull-right" href="documents/{{$dossier->media->url}}"><i class="fa fa-print"></i></a>
<br><br>
<button id="btn-add{{$dossier->id}}" class="btn btn-primary">Ajouter un Media</button>
#else
<div class="div1{{$dossier->id}}">
<div class="alert alert-warning">Aucune media</div><button id="btn-add{{$dossier->id}}" class="btn btn-primary">Ajouter un Media</button>
</div>
#endif

Looks like $dossier is null. You should always check if object is null, like:
#if (is_null($dossier) && $dossier->media)

Check your model Dossier, it may be like:
public function media(){
return $this->belongsTo('App\Media', MEDIA_FORIGNKEY);
}
Hope this help you!

Related

Cannot find parent element in DOM tree containing attribute: [wire:id]

I am laravel developer and developing a real time chat room using liveware , i am trying to open chat when i click to user but unfortunatly i am getting error https://flareapp.io/share/OmVDe437#F47 please help me how can resolved that ? thank u.
I am also getting error in console.
app\Http\Livewire\Messaging.php
public $selectedConservation;
public function mount(){
$this->selectedConservation = Conservation::query()
->where('sender_id',Auth::user()->id)
->orwhere('reciever_id',Auth::user()->id)
->first();
}
public function viewMessages($conservationsId){
$this->selectedConservation =
Conservation::findorFail($conservationsId);
}
public function render()
{
$conservation = Conservation::query()
->where('sender_id',Auth::user()->id)
->orwhere('reciever_id',Auth::user()->id)
->get();
return view('livewire.messaging',[
'conservation' => $conservation,
]);
}
resources\views\livewire\messaging.blade.php
#foreach ($conservation as $conservations)
<a href="#" wire:click.prevent="viewMessages({{ $conservations->id}} )">
<div class="user-card rounded bg-dark bg-opacity-10 mb-1">
<div class="mx-2">
<div class="d-flex pt-3">
<img class="rounded-circle" width="48px" height="48px" src="{{Config('wfh.file').$conservations->reciever->avator}}" alt="">
<div class="notification-text ms-3 w-100">
<span class="username fw-bold">{{$conservations->reciever->full_name}}</span>
<span class="float-end small"></span>
<p class="mt-1 text-muted">You: </p>
</div>
</div>
</div>
</div>
</a>
#endforeach
Check out the documentation on Dom Diffing Issues. It looks like you need to add a wire:key="{{ $conversations->id }}" attribute into your a tag so that Livewire can track changes to the list of conversations.

Error message "The GET method is not supported for this route. Supported methods: POST." in laravel 8

Following is my controller. Method ProjectsView is to view all the listings. The second method BackendProjectSearch is for searching of projects. The first page of search result is displayed properly, but when we click on next page it gives the error "The GET method is not supported for this route. Supported methods: POST."
What should I do ?
public function ProjectsView(){
$projects = projects::orderBy('id','ASC')->paginate(15);
return view('backend.projects.projects_view',compact('projects')); }
public function BackendProjectSearch(Request $request){
$request->validate(["search" => "required"]);
$item = $request->search;
$projects = Projects::where('project_name','LIKE',"%$item%")->paginate(15);
return view('backend.projects.projects_view',compact('projects')); }
Following are the routes for both the methods :
Route::post('/backend/project/search', [ProjectsController::class, 'BackendProjectSearch'])->name('backend.project.search');
Route::get('/view', [ProjectsController::class, 'projectsView'])->name('projects.view');
View code :
<div class="col-md-8">
<div class="header-navsearch">
<form class="form-inline mr-auto" method="post" action="{{route('backend.project.search')}}">
#csrf
<div class="nav-search">
<input type="search" name="search" class="form-control header-search" placeholder="Search projects…" aria-label="Search">
<button class="btn btn-primary" type="submit"><i class="fa fa-search"></i></button>
</div>
</form>
</div>
</div>
The route for this request should be post, not get.
Example
Route::post(-----);
Also, make sure to insert a CSRF token while making the request
it means you now cannot do something like the following.
Instead, you have to do something like...
<form action="{{ route('example') }}" method="POST">
#csrf {{-- According to the version of laravel --}}
{{-- Your other codes --}}
<button type="submit" class="">Submit</button>
</form>
You have to use the below code
return redirect()->route('projects.view')->with(['projects' => $projects]);
Your route might be little change
Route::get('/view/{projects?}', [ProjectsController::class, 'projectsView'])->name('projects.view');
and In your controller, you have to change function like this
public function ProjectsView($projects = null){
if($projects!=null){
return view('backend.projects.projects_view',compact('projects'));
}
else{
$projects = projects::orderBy('id','ASC')->paginate(15);
return view('backend.projects.projects_view',compact('projects'));
}

Laravel 2 submit buttons in the same form

I am building a CRUD with Laravel. Each category hasMany attachments and each attachment belongsTo a category.
In the category.edit view I want to give the user the possibility of deleting the attachments (singularly) from the Category. I tried this method but it did not work:
Registering route for the attachment:
Route::group(['middleware' => ['auth']], function () {
Route::delete('attachment/{id}', 'AttachmentController#delete')->name('attachment');
});
Handling the delete building the AttachmentController#delete method:
class AttachmentController extends Controller
{
public function delete($id) {
$toDelete = Attachment::findOrFail($id);
$toDelete->delete();
return redirect()->back();
}
}
In the CategoryController (edit method), I fetch the attachments linked to each category to be rendered inside the view:
public function edit($category)
{
$wildcard = $category;
$category = Category::findOrFail($wildcard);
$attachments = App\Category::findOrFail($wildcard)->attachments()->get()->toArray();
return view('category.edit', [
'category' => $category,
'attachments' => $attachments
]);
}
In the view, I render the attachment and the button to delete. I am fully aware of the error of having a form inside another form, nevertheless I do not know antoher approach to submit this delete request.
// update Category form
#foreach ($attachments as $attachment)
<div class="row">
<div class="col-4">
<img style="width: 100%;" src={{ $attachment['url'] }} alt="">
</div>
<div class="col-4">
<div>
<p class="general_par general_url">{{ $attachment['url'] }}</p>
</div>
</div>
<div class="col-4">
<form action="{{ route('attachment', $attachment['id']) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete Image</button>
</form>
</div>
</div>
<hr>
#endforeach
// end of update Category form
Should I build a deleteAttachment method inside the CategoryController? If so, how can I still submit the Delete request? Also, if any other Model in the future will have attachments, should I build a deleteAttachment method inside each controller? That is cumbersome. Thanks in advance
if you don't like to use form, then use tag:
<a class="btn btn-danger" href="{{ route('attachment', $attachment['id']) }}">Delete Image</a>
And redefine the route to Route::get(...)
(or maybe use ajax for POST method if that is required)

HOw to make simple search with laravel

i try to create forms search in laravel..
when the title of the title article is searched .. then the title will appear.. i am search title article form Article Table
this is my HomeController
...
public function search(Request $request){
$cari = $request->get('search');
$Title = Article::where('title', 'LIKE', '%' .$cari . '%')->paginate(10);
return view('/article/show', $cari);
}
this is my header.blade.php
**...
<div class = "col-md-4">
{!! Form::open(['method'=>'GET', 'url'=>'/article/show', 'role'=>'search']) !!}
<div class= "input-group custom-search-form">
<input type="text" class="form-control" name="search" placeholder="Judul..">
<span class="input-group-btn">
<span class="input-group-btn">
<button class="btn-btn-default" type="submit"><i class="fa fa-search"></i>Cari</button>
</span>
</span>
{!! Form::close()!! }
</div>
</div>
thi is my route..
..
Route::get('/article/show', 'HomeController#search');
.
But when i am typing on search form.. i am getting error like this
(2/2) QueryException
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'show AND is_show = TRUE and `articles`.`deleted_at` is null' at line 1 (SQL: select count(*) as aggregate from `articles` where category_id=show AND is_show = TRUE and `articles`.`deleted_at` is null)
.
please tell me which part is wrong
Thanks...
You're sending a POST request as GET. Switch the GET to POST, or include the searched term in the URL and remove the Request $request part of your search(Request $request) function since GET will not provide an instance of Request. Just make it search($terms) instead if you go that route. I would personally just switch to POST though.
IE:
Route::post('/article/show', 'HomeController#search');
{!! Form::open(['method'=>'POST', 'url'=>'/arti...
In your form add
{{ csrf_token() }}
Also you will want to check if 'search' has a value, so wrap it around a if ($request->search)
Also, it looks like you may have a SQL error somewhere else on the page which is cause this.
check your table name, or try this
public function search(Request $request)
{
$cari = $request->get('search');
$data['result']= DB::table('articles')->WHERE('title', 'LIKE', '%' .$cari . '%')->paginate(10);
return view('/article/show', $data);
}
your form
<form class="navbar-form navbar-left" method="GET" action="{{url('search')}}">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="search">
<button class="btn btn-default" type="submit">
<i class="fa fa-search"></i>
</button>
</div>
</form>

My function is deleting a different row to the one I intended, Laravel 5.4?

When I press remove, it removes the last charity in the database that belongs to the current user.
View (Button that deletes):
<a href="#"> <button class="btn btn-danger pull-right btnPopover" data-
toggle="popover" data-placement="top"> Remove </button> </a>
View (JS that is called):
function ConfirmDelete()
{
true;
}
$(document).ready(function()
{
$('.btnPopover').popover(
{
html: 'true',
title: '<strong> Are you sure you want to Remove? </strong>',
content: '<form style="display: inline;" action="{{
URL::to('remove', array($favourite->id)) }} "> <button class = "btn
btn-success glyphicon glyphicon-ok" onclick="return
ConfirmDelete()"> Yes </button> </form> <button class = "btn btn-
danger glyphicon glyphicon-remove"> No </button> '
});
$('.btnPopover').on('click', function (e)
{
$('.btnPopover').not(this).popover('hide');
});
Route:
Route::get('remove/{id}', 'HomeController#removeFavourite');
Controller (removeFavourite function):
public function removeFavourite($id)
{
Favourites::where('id', $id)->delete();
Session::flash('flash_message', 'Removed successfully!');
return back();
}
The strange thing is, is that I am using the exact same function and JS call in another part of the application and it is working fine!
The problem is, that it deletes the last record belonging to that user in the database.
Thanks
I don't know exactly what your code looks like, but the problem is that your JS is only valid for the last iteration of the loop, which sounds like what you're experiencing.
To fix it, you can move the form inside the popover button so that you can get the correct form link:
Example (moving the form):
<button class="btn btn-danger pull-right btnPopover" data-toggle="popover" data-placement="top" data-content='<form style="display: inline;" action="{{ URL::to('remove', array($favourite->id)) }} "> <button class = "btn btn-success glyphicon glyphicon-ok" onclick="return ConfirmDelete()"> Yes </button> </form> <button class = "btn btn-danger glyphicon glyphicon-remove"> No </button> '> Remove </button>
JS:
$(document).ready(function()
{
$('.btnPopover').popover(
{
html: 'true',
title: '<strong> Are you sure you want to Remove? </strong>',
});
$('.btnPopover').on('click', function (e)
{
$('.btnPopover').not(this).popover('hide');
});
....
This could be a little cleaner if you could access the parent button from the popover, but I couldn't find a way to do that in the API.
Check whether the $id you retrieve in your program(I assume there is some code missing in the question which finds the $id) is the one you want to delete.
Level official documentation says to use following code for deleting models:
$flight = App\Flight::find(1);
$flight->delete();
Find retrieves single model, and where returns a collection, so that might be the issue.
Also make sure that you pass the specific $id of the favourite that needs to be deleted, if not you'll always be deleting the last $id in your loop.
Official Docs

Resources